Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use these @DataMongoTest and @SpringBootTest together in integration test

I am trying to write integration test case for one of my rest application which uses mongodb internally to persist the data

@DataMongoTest 
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class MainControllerTest {
@LocalServerPort
    private int port = 8080;
/* some test cases*/ 
}

but I am getting below error

java.lang.IllegalStateException: Configuration error: found multiple declarations of @BootstrapWith for test class [com.sample.core.controller.MainControllerTest]: [@org.springframework.test.context.BootstrapWith(value=class org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTestContextBootstrapper), @org.springframework.test.context.BootstrapWith(value=class org.springframework.boot.test.context.SpringBootTestContextBootstrapper)]

looks like these two are mutually exclusive, so how to do the integration testing .

like image 953
kcoder Avatar asked Apr 02 '19 11:04

kcoder


People also ask

What is the effect of adding the @SpringBootTest annotation to a test class?

The @SpringBootTest annotation loads the complete Spring application context. In contrast, a test slice annotation only loads beans required to test a particular layer. And because of this, we can avoid unnecessary mocking and side effects.

How do you perform integration testing with @SpringBootTest for a Web application?

Write an End-To-End Test With a Running Server To provide a real web environment, we can tell Spring Boot to do that: @SpringBootTest(webEnvironment = SpringBootTest. WebEnvironment. RANDOM_PORT) @ActiveProfiles("test") class ServerIntegrationTests { @Autowired private WebTestClient webClient; // ... }

What is @SpringBootTest used for?

Spring Boot provides a @SpringBootTest annotation, which can be used as an alternative to the standard spring-test @ContextConfiguration annotation when you need Spring Boot features. The annotation works by creating the ApplicationContext used in your tests through SpringApplication .

How are you going to create an ApplicationContext in an integration test?

To create integration test in Spring make sure that you have Spring Test in your dependencies and, for example, JUnit. Then you need to put annotation @RunWith(SpringRunner. class) on the test class. And also add Context Configuration to your test with a list of configs in annotation @ContextConfiguration.


1 Answers

Use @AutoConfigureDataMongo with @SpringBootTest and this will resolve this ambiguity issue. @SpringBootTest and @DataMongoTest cannot be used together.

like image 51
Jestin Mathew Avatar answered Oct 18 '22 10:10

Jestin Mathew