piotrek
piotrek

Reputation: 14550

Spring boot: how to add spring-data repositories in tests

In tests i can add any bean (using static nested configuration class). but how can i add spring-data repositories? i can't return then as new bean because i can't instantiate them - they are interfaces

@RunWith(SpringRunner.class)
@DataMongoTest
//@SpringBootTest   // or this annotation
public class JTest {

    @Configuration
    static class Config {

        static class TestEntity {
            String id;
        }

        interface TestRepository extends ReactiveMongoRepository<TestEntity, String> {}

    }

    @Autowired Config.TestRepository testRepository;

    @Test
    public void test() {}
}

running with @DataMongoTest gives me

Caused by: java.lang.IllegalStateException: Unable to retrieve @EnableAutoConfiguration base packages

running with @SpringBootTest gives:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'xxx.JTest$Config$TestRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

how can i add new repositories in tests?

Upvotes: 2

Views: 1539

Answers (1)

夢のの夢
夢のの夢

Reputation: 5846

Spring doesn't pick up nested interface repository (and instantiate a bean) by default. To enable, see:

@RunWith(SpringRunner.class)
@DataMongoTest
@EnableMongoRepositories(considerNestedRepositories = true)
public class JobTest {

    @TestConfiguration
    static class Config {

        static class TestEntity {
            String id;
        }
    ....

Internally, Spring registers a bean with new SimpleMongoRepository<T, ID>(..) if none other specified.

Edit Just realized you are using reactive Mongo. So switch to EnableReactiveMongoRepositories(..) instead.

Upvotes: 2

Related Questions