我正在尝试禁用真正的 Mongo 连接并在测试中用 Fongo 模拟替换它。
这是我的测试课:
@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 ...
}
}
除非我尝试添加更改此行的配置文件,否则它工作正常:
@SpringBootTest
对此:
@SpringBootTest(classes = TestConfig.class)
配置类本身:
@Configuration
@ComponentScan
@EnableMongoRepositories
public class TestConfig extends AbstractMongoConfiguration {
@Override
protected String getDatabaseName() {
return "FongoDB";
}
@Override
public Mongo mongo() {
return new Fongo(getDatabaseName()).getMongo();
}
}
然后应用程序找不到 bean 并抛出下一个异常:
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
如何修复它并正确应用其他配置?