好像我在这里遗漏了一些重要的东西,但我自己没有设法找到它。
我有一个 Spring Boot 应用程序和 Hibernate,我正在尝试通过一些集成测试进行测试。我在测试时使用 HSQL 数据库。我尝试运行的测试使用 MockMvc 来检查我的控制器返回的 json 响应。
我让我的测试类扩展了一个配置类,它使用@Before 和@After 来初始化测试数据并在之后将其删除。
因此,在我的单一测试课程中,我有四个测试。只是做一些简单的、基本的事情,比如返回列表和单个对象。他们都只是在读取数据。
@Test
public void testGetSingleData() throws Exception {
this.mockMvc.perform(get("/api/data/{id}", 1)
.andExpect(status().isOk());
}
@Test
public void testGetListData() throws Exception {
this.mockMvc.perform(get("/api/data/", 1)
.andExpect(status().isOk());
}
…
and so on.
发生的情况是,当我分别运行这些测试时,一次一个,它们都运行良好。我得到了预期的输出。但是,当同时运行这四个测试时,其中之一没有返回相同的响应。事实上,它什么也没返回。更具体地说, testGetSingleData 测试在单独运行时返回一个对象。当与其他测试一起运行时,它什么也不返回。我的控制器说数据不在数据库中。在我看来,测试之间的数据库正在发生一些事情。当然,数据已初始化并删除,但这应该没问题。例如,一起运行返回对象列表的两个测试可以正常工作,但不能与返回单个对象的测试一起运行。因此,当 testGetSingleData 运行时,数据不知何故消失了。我想我需要一个潜在的原因来解释为什么会发生这种情况。单独运行的测试与其他测试一起运行时无法运行的错误来源可能是什么?
我的班级«test-config-class»注释为:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(loader = SpringockitoAnnotatedWebContextLoader.class, classes = Application.class)
@TestPropertySource(locations = "classpath:config/application.properties")
编辑:
@Autowired
private EntityManagerFactory firstDbEntityManager;
@Autowired
private EntityManagerFactory secondDbEntityManager;
protected SessionFactory firstDbSessionFactory;
protected SessionFactory secondDbSessionFactory;
@Before
public void initSessionFactories() {
if (firstDbSessionFactory == null) {
firstDbSessionFactory = firstDbEntityManager.unwrap(SessionFactory.class);
}
if (secondDbSessionFactory == null) {
secondDbSessionFactory = secondDbEntityManager.unwrap(SessionFactory.class);
}
initTestData();
}
@After
public void cleanDatabase() {
doCleanDatabase(firstDbEntityManager);
doCleanDatabase(secondDbEntityManager);
}
private void doCleanDatabase(EntityManagerFactory entityManagerFactory) {
Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
session.createSQLQuery("truncate schema public and commit").executeUpdate();
session.flush();
session.close();
}