5

我正在尝试禁用真正的 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

如何修复它并正确应用其他配置?

4

2 回答 2

4

尝试使用

  • @SpringBootTest @Import(value = TestConfig.class)

而不是 @SpringBootTest(classes = TestConfig.class)

于 2018-12-04T08:24:06.747 回答
1

保留@SpringBootTest,然后使用@TestConfiguration 和bean 创建一个类,如下所示:

@TestConfiguration
public class TransactionManagerTestConfiguration {

   @Bean
   public String getDatabaseName() {
       return "FongoDB";
   }

   @Bean
   public Mongo mongo() {
       return new Fongo(getDatabaseName()).getMongo();
   }
}

根据 javadoc:可用于为测试定义其他 bean 或自定义的配置。与常规 Configuration 类不同,TestConfiguration 的使用不会阻止 SpringBootConfiguration 的自动检测

于 2019-06-27T15:38:10.757 回答