jsosnowski
jsosnowski

Reputation: 1590

Use Spring JpaRepository in test

I have Spring Boot application with configuration:

@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true, prePostEnabled=true)
@EnableJpaRepositories(basePackages = "com.site.data.repository")
@EntityScan(basePackages = "com.site.data.entity")
@ComponentScan(basePackages = "com.*")
@SpringBootApplication
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

And in resources folder there is application.properties file:

spring.datasource.url=...
spring.datasource.username=...
spring.datasource.password=...
spring.datasource.driverClassName=...
#...

Problem:

I try to make new class which will add some entries to database. I thought that the best solution is making a JUnit test class. So if anybody wants to feed my database he could simply run this specific test:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = WebSecurityConfig.class)
public class DataFeeder {
    @Autowired
    MyRepository myRepository;

    @Test
    public void feedDB() {
        MyEntity entity = new MyEntity();
        myRepository.saveAndFlush(entity);
    }
}

But this configuration doesn't work. Of course all repositories work great in project. But during running test I obtain messages that all tables don't exist. For example for SOME_TABLE:

Table "SOME_TABLE" not found; SQL statement:

I saw a lot of tutorials about how to test JpaRepository, but I don't want make test, which add some items and delete it after test end. I simply want save some data in database (but in @Test function)

What is wrong with my configuration?

Upvotes: 0

Views: 1792

Answers (1)

Jens
Jens

Reputation: 69440

use @SpringApplicationConfiguration instead of @ContextConfiguration. this is needed for Spring-boot application tests.

Upvotes: 1

Related Questions