The @PropertyMapping annotation @WebMvcTest cannot

2019-08-05 01:33发布

问题:

I have a Spring MVC test:

@RunWith(SpringRunner.class)
@WebMvcTest
@Configuration
public class InventoryControllerIntegrationTest {

    @MockBean
    private InventoryService inventoryService;

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void shouldReturnInventory() throws Exception {
        this.mockMvc.perform(get("/inventory")).andDo(print()).andExpect(status().isOk())
                .andExpect(content().string(containsString("Hello World")));
    }

}

And a corresponding controller.

After running the test I get the exception:

2018-01-27 21:28:25.099 ERROR 12470 --- [           main] o.s.test.context.TestContextManager      : Caught exception while allowing TestExecutionListener [org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@6df37f7a] to prepare test instance [com.video.rental.store.videorentalstore.inventory.InventoryControllerIntegrationTest@21d3d6ec]

java.lang.IllegalStateException: The @PropertyMapping annotation @WebMvcTest cannot be used in combination with the @Component annotation @Configuration
        at org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer$PropertyMappingCheckBeanPostProcessor.postProcessBeforeInitialization(PropertyMappingContextCustomizer.java:99) ~[spring-boot-test-autoconfigure-1.5.9.RELEASE.jar:1.5.9.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:409) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]

How do I go around this and add the mock bean inventoryService?