当前位置: 首页 > 知识库问答 >
问题:

使用jUnit进行Spring Hibernate存储库测试

裘嘉树
2023-03-14

首先,我是Spring Hibernate开发的新手。遵循了很多教程书籍,我创建了一个主要基于Spring、Hibernate标准的示例应用程序,我已经开始为Repository(DAO)方法编写一些测试用例,即查找、查找、保存、删除。

当我执行测试类时,这真是太疯狂了,并不是所有的测试用例都能正确地为ex执行。尤其是find

@Entity
@Table(name = "client_master")
public class ClientMaster {

private Long id;
private Long version;
private Date dateCreated;
private Date lastUpdated;
private String clientName;

private List<ProjectMaster> projectMaster;

@Id
@GeneratedValue
public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

@Version
@Column(name = "version")
public Long getVersion() {
    return version;
}

public void setVersion(Long version) {
    this.version = version;
}

@Column(name = "client_name", nullable= false,unique= true)
public String getClientName() {
    return clientName;
}

public void setClientName(String clientName) {
    this.clientName = clientName;
}

@OneToMany(targetEntity = ProjectMaster.class, mappedBy = "lientMaster", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
public List<ProjectMaster> getProjectMaster() {
    return projectMaster;
}

public void setProjectMaster(List<ProjectMaster> ProjectMaster) {
    this.projectMaster = projectMaster;
}

@Column(name = "date_created" , nullable= false)
@Temporal(TemporalType.TIMESTAMP)
public Date getDateCreated() {
    return dateCreated;
}

public void setDateCreated(Date dateCreated) {
    this.dateCreated = dateCreated;
}

@Column(name = "last_updated")
@Temporal(TemporalType.TIMESTAMP)
public Date getLastUpdated() {
    return lastUpdated;
}

public void setLastUpdated(Date lastUpdated) {
    this.lastUpdated = lastUpdated;
}

}  
import java.util.List;
import javax.persistence.EntityNotFoundException;
import org.hibernate.Query;

@Repository("clientMasterRepo")
@Transactional
public class ClientMasterRepoHibernate implements ClientMasterRepository {

@Autowired
private SessionFactory sessionFactory;

@Override
public ClientMaster find(Long id) {     
    // Based on the Hibernate currentsession get the ClientMaster Object based on Id        
    ClientMaster clientMaster = (ClientMaster) sessionFactory.getCurrentSession().get(ClientMaster.class, id);              
    return clientMaster;
}

@Override
public List<ClientMaster> findAll() {
    // Get all the ClientMaster records.
    Query query = sessionFactory.getCurrentSession().createQuery("FROM ClientMaster");
    List<ClientMaster> clientMasterList = query.list();
    return clientMasterList;

}

@Override
public ClientMaster save(ClientMaster clientMaster) {
    // Insert or Update the ClientMaster object
    sessionFactory.getCurrentSession().saveOrUpdate(clientMaster);
    return CclientMaster;       
}

@Override
public void delete(ClientMaster clientMaster) {
    // Delete the ClientMaster object
    sessionFactory.getCurrentSession().delete(clientMaster);
}

}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"file:src/main/resources/META-INF/spring/spring-master.xml"})  
public class ClientMasterRepositoryTests {

@Autowired
private ClientMasterRepository clientMasterRepository;

private List<ClientMaster> ClientMasterList;

@Before
public void setup(){
    // Initialize ClientMaster mock objects for testing     
    ClientMasterList = new ArrayList<ClientMaster>();

    ClientMaster client1 = new ClientMaster();
    client1.setClientName("Client1");
    client1.setDateCreated(new Date());
    client1.setLastUpdated(new Date());

    ClientMaster client2 = new ClientMaster();
    client2.setClientName("Client2");
    client2.setDateCreated(new Date());
    client2.setLastUpdated(new Date());

    ClientMaster client3 = new ClientMaster();
    client3.setClientName("Client3");
    client3.setDateCreated(new Date());
    client3.setLastUpdated(new Date());

    ClientMaster client4 = new ClientMaster();
    client4.setClientName("Client4");
    client4.setDateCreated(new Date());
    client4.setLastUpdated(new Date());

    ClientMasterList.add(client1);
    ClientMasterList.add(client2);
    ClientMasterList.add(client3);
    ClientMasterList.add(client4);      
}

@Test
public void testSave(){     
    for (Iterator iterator = ClientMasterList.iterator(); iterator.hasNext();) {
        ClientMaster ClientMaster = (ClientMaster) iterator.next(); 

        // insert the ClientMaster object 
        clientMasterRepository.save(ClientMaster);

        assertTrue(ClientMaster.getClientName()+" is saved - Id "+ClientMaster.getId(),ClientMaster.getId() > 0);
    }       
}

@Test
public void testUpdate(){
    // get a ClientMaster object from the repository
    ClientMaster clientMasterObj = clientMasterRepository.find(1L);

    // assert if its not null
    assertTrue(!clientMasterObj.getClientName().isEmpty());

    // change the client name 
    clientMasterObj.setClientName("Client1-Changed");

    // update the ClientMaster object
    clientMasterRepository.save(clientMasterObj);

    // assert the value changed id true
    assertEquals("Client1-Changed", clientMasterRepository.find(1L).getClientName());
}

@Test   
public void testDelete(){
    // get a CASClientMaster object from the repository
    ClientMaster clientMasterObjBeforeDel = clientMasterRepository.find(2L);

    // delete the ClientMaster object
    clientMasterRepository.delete(clientMasterObjBeforeDel);

    // get a ClientMaster object from the repository
    ClientMaster clientMasterObjAfterDel = clientMasterRepository.find(2L);

    // get the ClientMaster object ID 
    assertNull(clientMasterObjAfterDel);
}

@Test
public void testFind(){

    // get a ClientMaster object from the repository
    ClientMaster clientMasterObj = clientMasterRepository.find(3L);             

    // compare the id's of passed and retrieved objects.
    assertThat(clientMasterObj.getId(), is(3L));
    assertTrue(clientMasterObj.getId() == 3);       
}

@Test
public void testFindAll(){
    // get all ClientMaster object from the repository 
    List<ClientMaster> ClientMasterList = clientMasterRepository.findAll();             

    // check if it returns all records from DB
    assertTrue(ClientMasterList.size() > 0);
    assertThat(ClientMasterList.size(), is(4));
}

}

当我完全执行以上所有测试用例时

甚至更新测试用例的行为也很奇怪,因为在某些情况下,某些执行工作正常。当我使用find方法获取clientMaster对象时,它会给出“NullPointerException”错误。

共有1个答案

曾元忠
2023-03-14

您的测试不会自动重置持久化的数据。有几个解决或解决这个问题的替代方案:

1.将@Transactional注释添加到测试中。

事务测试在测试完成后回滚的事务中运行,清除测试保留的任何状态。但是,添加@Transactional可能会隐藏一些错误。请参阅有关它的这篇文章。

2.创建一个@After方法来清除任何持久的更改

这可能很难维护,因为您需要跟踪测试持续存在的所有内容。一种稍微复杂但可维护的方法是在运行测试之前转储数据库,然后在每次测试之后从该转储中恢复它。

3.以一种即使数据库已经包含某些内容也不会中断的方式实现测试。

示例:

@Test
public void testEntityGetsPersisted() {
    int countBefore = getCurrentCountOfEntities();
    persistNewEntity();
    int countAfter = getCurrentCountOfEntities();
    assertTrue(countAfter == countBefore + 1);
}
 类似资料:
  • ...还有一个很简单的测试... 如果我在IntelliJ中运行这个,测试就会运行并失败。 如果我提交这个项目并将其推送到github,TeamCity会看到变化并开始构建。生成会很快失败,出现以下错误:

  • 我正在开发一个基于spring boot的webservice,其结构如下: 控制器(REST)-->服务-->存储库(如某些教程中所建议的)。

  • 我有这个过滤器类,在使用junit进行测试时需要尽可能高的代码覆盖率。 和测试等级: 当我运行时,它在 线 我如何避免这种情况? 我需要调用这个方法并执行里面的任何内容来提供所需的代码覆盖。

  • 我正在使用Jenkins CI构建我的iOS项目。对于这个任务,我使用sh脚本通过运行xcodebuild直接从git repo构建二进制文件,这很好。目前,我使用eclipse中的appium运行JUnit测试来测试我的应用程序,但我也想将它们集成到Jenkins中。我找到了一些使用ant脚本将JUnit测试集成到jenkins中的教程,但我没有使用ant来构建我的项目。没有ant脚本,我如何将

  • 问题内容: 也许我的问题是新手,但是我真的无法理解在什么情况下使用junit? 无论是编写简单的应用程序还是大型应用程序,我都使用语句对其进行测试,这对我来说很容易。 如果仍然需要调用相同的方法,检查它们返回的内容,然后又要为所有内容添加注释,那么为什么要使用JUnit创建测试类,在项目中创建不必要的文件夹呢? 为什么不编写一个类并立即对其进行测试而不创建Test-class? PS。我从未在刚刚

  • 我现在开始使用JUnit5和Spring Boot的测试。我有一个包含控制器、服务和存储库的Rest API,以及一些使用从我的获取属性的utils类。我没有使用Spring中的“profiles”,只是使用默认配置。 我的应用程序主: 我的项目的体系结构是: 我在主测试类中尝试了“@TestPropertySource”和/或“@ActiveProfiles(”Test“)”,但没有成功。还尝试