简体   繁体   中英

SpringBoot - Junit test not Rollingback using JdbcTemplate for H2

I've generated a Spring Boot web application using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.

Technologies used:

Spring Boot 1.4.2.RELEASE, Spring 4.3.4.RELEASE, Thymeleaf 2.1.5.RELEASE, Tomcat Embed 8.5.6, Maven 3, Java 8

I have this test, that is failing, because Junit test is not rolling back the insert 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 annotation works only if transaction management happens through Jpa/Hibernate/JdbcTemplate (the annotation influence on transaction only if the transaction is managed by some PlatformTransactionManager ).

It looks like JdbcGuardianRepository uses plain jdbc access (or something like that) and spring cannot know anything about your transactions.

Consider using JPA to manage transactions and you'll solve the problem.

Alternatively you can annotate your test class with @Sql("/clean-db.sql") and provide some cleanup sql code inside clean-db.sql . Spring will run this script before every test run. Consider adding more information about JdbcGuardianRepository if this does not solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM