Adding configuration class to SpringBootTest break

2020-04-21 07:03发布

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?

2条回答
Melony?
2楼-- · 2020-04-21 07:28

try use

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

instead of @SpringBootTest(classes = TestConfig.class)

查看更多
欢心
3楼-- · 2020-04-21 07:42

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.

查看更多
登录 后发表回答