Tomasz Bawor
Tomasz Bawor

Reputation: 1657

Spring Boot trying to create mongo repositories in tests using @JsonTest annotations

I have an application using SpringBoot2 with mongodb and I am trying to test json serialization of some DTOS by making tests like:

@JsonTest
@RunWith(SpringRunner.class)
public class SomeDTOTest {
    @Autowired
    JacksonTester < SomeDTO > json;

    @Test
    public void someTest() {}
}

However underneath spring is trying to create repository bean and giving me informations:

***************************
APPLICATION FAILED TO START
***************************

Description:

A component required a bean named 'mongoTemplate' that could not be found.


Action:

Consider defining a bean named 'mongoTemplate' in your configuration.

I have more integration test that is using the repository and are annotated with @SpringBootTests and they are working fine...

Is there a way of restricting spring to only creating JacksonTester bean?

Upvotes: 0

Views: 1903

Answers (2)

Abbas Hosseini
Abbas Hosseini

Reputation: 747

I found it quite challenging to have both Integration tests as well as Unit tests in a Spring Boot application. I checked Spring website and tried many solutions. The one that worked for me was to exclude the AutoConfiguration classes:

 @RunWith(SpringRunner.class)
 @JsonTest(excludeAutoConfiguration = EmbeddedMongoAutoConfiguration.class)
 public class JsonTests {

      @Autowired
      private JacksonTester json;

      @MockBean
      private MyRepository repository;

      @MockBean
      private MongoTemplate mongoTemplate;

      @Test
      public void someTest() {}
 }      

You can find a complete Spring Boot application that include Integration and Unit tests here.

Upvotes: 1

kimy82
kimy82

Reputation: 4495

You could just create a test without spring runner.

This is an example example test

When loading the spring context if there is an autowired annotation of a mongotemplate somewhere spring will try to provide it. You might consider:

  1. Provided mongo template in tests

    Try using @DataMongoTest which will provide an embedded database.

  2. Set an Autowired not required

    Use @Autowired(required= false)

  3. Mock mongotemplate

    Use @MockBean annotation in order to mock mongoTemplate

Upvotes: 1

Related Questions