1
votes

I am trying to test a JpaRepository with spring boot integration tests. I'm using the @DataJPATest annotation without the embedded db. I'm using the same MySQL db that I use for development to run integration tests.

@DataJpaTest
@AutoConfigureTestDatabase(replace = NONE)
class UserRepositoryTest {

    @Autowired
    UserRepository userRepository;

    @Test
    void findByUsername() {
        User u = new User();
        u.setUsername("ML");
        u.setFirstname("Micheal");
        u.setLastname("Lane");
        u.setActive(true);
        userRepository.save(u);
        assertThat(userRepository.findByUsername("M21")).isNotNull();
    }
}

The value I inserted in the test is inserted into the actual data base. But I thought with @DataJpaTest the transaction is rolled back at the end of the test.

By default, tests annotated with @DataJpaTest are transactional and roll back at the end of each test. They also use an embedded in-memory database (replacing any explicit or usually auto-configured DataSource). The @AutoConfigureTestDatabase annotation can be used to override these settings.

So why is my data getting saved to the database? Is it because I'm not using the embedded database?

Dialect used : spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

**********************************************************8

It started to rollback once I remove findByUsername() part form the test method

 User u = new User();
        u.setUsername("ML");
        u.setFirstname("Micheal");
        u.setLastname("Lane");
        u.setActive(true);
        userRepository.save(u);
        //assertThat(userRepository.findByUsername("M21")).isNotNull();

So I guess It doesn't work because there are 2 queries. I will have to use an already saved data for findByUsername() test

2
which dialect are you using? Can you post it in question? Also spring version.wak786
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5DialectUserR

2 Answers

1
votes

I believe it is due to the auto-wire. When you auto-wire it instantiates the interface via dependency injections. If you don't want data to be stored when running the test I suggest you look at mockito. There you can mock the repos so you can test all the methods used when storing data but never actually saves it

0
votes

Can you try by using this dialect.

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

Hope this should work.