I am trying to disable real Mongo connection and replace it with Fongo mock in tests.
Here is my test class:
@SpringBootTest
@RunWith(SpringRunner.class)
public class ControllerTest {
@Autowired
private WebApplicationContext wac;
@Autowired
private ObjectMapper objectMapper;
@MockBean
private MyService service;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void performTest() throws Exception {
... logic ...
}
}
It works fine unless I try to add my configuration file changing this line:
@SpringBootTest
to this:
@SpringBootTest(classes = TestConfig.class)
config class itself:
@Configuration
@ComponentScan
@EnableMongoRepositories
public class TestConfig extends AbstractMongoConfiguration {
@Override
protected String getDatabaseName() {
return "FongoDB";
}
@Override
public Mongo mongo() {
return new Fongo(getDatabaseName()).getMongo();
}
}
Then application fails to find beans and throws the next exception:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.fasterxml.jackson.databind.ObjectMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
... 28 more
How can I fix it and apply additional configuration properly?
try use
instead of @SpringBootTest(classes = TestConfig.class)
keep @SpringBootTest and then create a class using @TestConfiguration with the beans in as follows:
@TestConfiguration
public class TransactionManagerTestConfiguration {
@Bean
public String getDatabaseName() {
return "FongoDB";
}
@Bean
public Mongo mongo() {
return new Fongo(getDatabaseName()).getMongo();
}
}
As per the javadoc: Configuration that can be used to define additional beans or customizations for a test. Unlike regular Configuration classes the use of TestConfiguration does not prevent auto-detection of SpringBootConfiguration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With