SpringBoot - Junit 测试不使用 H2 的 JdbcTemplate 回滚
SpringBoot - Junit test not Rollingback using JdbcTemplate for H2
我使用 Spring 初始化器生成了一个 Spring 启动 Web 应用程序,嵌入 Tomcat,Thymeleaf 模板引擎,并打包为可执行 JAR 文件。
使用的技术:
Spring 引导 1.4.2.RELEASE、Spring 4.3.4.RELEASE、Thymeleaf 2.1.5.RELEASE、Tomcat 嵌入 8.5.6 , 行家 3, Java 8
我有这个测试,但失败了,因为 Junit 测试没有回滚插入 java.lang.AssertionError: expected:<1> but was:<2>
@ContextConfiguration(classes={PersistenceConfig.class})
@RunWith(SpringRunner.class)
public class JdbcGuardianRepositoryTests {
@Autowired
private JdbcGuardianRepository repository;
@Test
public void testGetAllGuardians() throws DataAccessException, SQLException {
assertEquals(1, repository.getAllGuardians(null).size());
}
@Test
@Rollback
public void testInsetGuardian() throws DataAccessException, SQLException {
Guardian newGuardian = new Guardian();
newGuardian.setDescription("bob desc");
newGuardian.setEmail("bob@gmail.com");
newGuardian.setId(Sequencer.getNextVal());
newGuardian.setMobile("123456789");
newGuardian.setName("bob");
newGuardian.setSurName("bob surname");
assertNotEquals(-1, repository.insert(newGuardian));
}
}
@Rollback
注解只有在通过 Jpa/Hibernate/JdbcTemplate 进行事务管理时才有效(只有当事务由某些 PlatformTransactionManager
管理时,注解才会影响事务)。
看起来 JdbcGuardianRepository
使用普通的 jdbc 访问权限(或类似的东西)并且 spring 无法了解您的交易。
考虑使用JPA来管理事务,问题就迎刃而解了。
或者,您可以使用 @Sql("/clean-db.sql")
注释您的测试 class 并在 clean-db.sql
中提供一些清理 sql 代码。 Spring 将在每次测试前 运行 此脚本 运行。
如果这不能解决您的问题,请考虑添加有关 JdbcGuardianRepository
的更多信息。
我使用 Spring 初始化器生成了一个 Spring 启动 Web 应用程序,嵌入 Tomcat,Thymeleaf 模板引擎,并打包为可执行 JAR 文件。
使用的技术:
Spring 引导 1.4.2.RELEASE、Spring 4.3.4.RELEASE、Thymeleaf 2.1.5.RELEASE、Tomcat 嵌入 8.5.6 , 行家 3, Java 8
我有这个测试,但失败了,因为 Junit 测试没有回滚插入 java.lang.AssertionError: expected:<1> but was:<2>
@ContextConfiguration(classes={PersistenceConfig.class})
@RunWith(SpringRunner.class)
public class JdbcGuardianRepositoryTests {
@Autowired
private JdbcGuardianRepository repository;
@Test
public void testGetAllGuardians() throws DataAccessException, SQLException {
assertEquals(1, repository.getAllGuardians(null).size());
}
@Test
@Rollback
public void testInsetGuardian() throws DataAccessException, SQLException {
Guardian newGuardian = new Guardian();
newGuardian.setDescription("bob desc");
newGuardian.setEmail("bob@gmail.com");
newGuardian.setId(Sequencer.getNextVal());
newGuardian.setMobile("123456789");
newGuardian.setName("bob");
newGuardian.setSurName("bob surname");
assertNotEquals(-1, repository.insert(newGuardian));
}
}
@Rollback
注解只有在通过 Jpa/Hibernate/JdbcTemplate 进行事务管理时才有效(只有当事务由某些 PlatformTransactionManager
管理时,注解才会影响事务)。
看起来 JdbcGuardianRepository
使用普通的 jdbc 访问权限(或类似的东西)并且 spring 无法了解您的交易。
考虑使用JPA来管理事务,问题就迎刃而解了。
或者,您可以使用 @Sql("/clean-db.sql")
注释您的测试 class 并在 clean-db.sql
中提供一些清理 sql 代码。 Spring 将在每次测试前 运行 此脚本 运行。
如果这不能解决您的问题,请考虑添加有关 JdbcGuardianRepository
的更多信息。