【问题标题】:SpringBoot - Junit test not Rollingback using JdbcTemplate for H2Spring Boot - Junit 测试不使用 JdbcTemplate 回滚 H2
【发布时间】:2017-08-01 23:05:18
【问题描述】:

我使用 Spring Initializer、嵌入式 Tomcat、Thymeleaf 模板引擎生成了一个 Spring Boot Web 应用程序,并将其打包为可执行 JAR 文件。

使用的技术:

Spring Boot 1.4.2.RELEASE、Spring 4.3.4.RELEASE、Thymeleaf 2.1.5.RELEASE、Tomcat 嵌入 8.5.6、Maven 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));
    }
}

【问题讨论】:

  • 它究竟是如何“失败”的?

标签: java spring spring-boot junit4 h2


【解决方案1】:

@Rollback 注解仅在事务管理通过 Jpa/Hibernate/JdbcTemplate 发生时才有效(该注解仅在事务由某些PlatformTransactionManager 管理时才会影响事务。

看起来JdbcGuardianRepository 使用普通的 jdbc 访问(或类似的东西),而 spring 对您的交易一无所知。

考虑使用 JPA 来管理事务,您将解决问题。

或者,您可以使用@Sql("/clean-db.sql") 注释您的测试类,并在clean-db.sql 中提供一些清理sql 代码。 Spring 将在每次测试运行之前运行此脚本。 如果这不能解决您的问题,请考虑添加有关 JdbcGuardianRepository 的更多信息。

【讨论】:

    猜你喜欢
    • 2012-10-24
    • 2021-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    • 2019-04-01
    相关资源
    最近更新 更多