Spring Boot - Test for controller fails with 404 code

后端 未结 8 1125
一个人的身影
一个人的身影 2021-01-04 18:17

I want to write a test for controller. Here is test snippet:

@RunWith(SpringRunner.class)
@WebMvcTest(WeatherStationController.class)
@ContextConfiguration(c         


        
相关标签:
8条回答
  • 2021-01-04 18:53

    After some debugging, it appears that the target controller is simply not registered as a method handler. Spring scans the beans for the presence of RestController annotation.

    But the problem is that the annotation could be found only if the bean is proxied via CGLIB, but for the case when we use WebMvcTest it's proxied by JDK.

    As a result, I searched for the configuration which is responsible for making the choice, and the one was finally found AopAutoConfiguration. So when SpringBootTest is used this one is autoloaded when you need WebMvcTest+PreAuthorize in your controllers, then simply use:

    @Import(AopAutoConfiguration.class)
    
    0 讨论(0)
  • 2021-01-04 18:57

    I import external configuration class by @ContextConfiguration(classes = MyConfig.class)

    When I changed in MyConfig annotation @Configuration into @TestConfiguration it started to work properly.

    0 讨论(0)
提交回复
热议问题