spring-boot icon indicating copy to clipboard operation
spring-boot copied to clipboard

No handlers found in WebMvcTest for proxied RestController

Open raddatzk opened this issue 3 years ago • 4 comments

Affected Version: 2.7.5

I created a @WebMvcTest for a controller that implements a generated interface from an openapi spec. When one of the implemented handlers for example is annotated with @PreAuthorized, in case of a @WebMvcTest spring will create a JdkProxy, in the case when starting this application regularly it will create a cglib proxy.

Unfortunately spring will not detect any handlers in the case of a @WebMvcTest, as it can't find any annotations on the JdkProxy (RequestMappingHandlerMapping:isHandler(Class<?>)) and the test will fail with a 404.

I would expect that both cases will behave similar

raddatzk avatar Nov 29 '22 19:11 raddatzk

Can you please share a minimal sample that reproduces the problem?

wilkinsona avatar Nov 29 '22 20:11 wilkinsona

https://github.com/raddatzk/spring-boot-33415

The ApplicationTest succeeds while PeopleControllerTest fails with 404

raddatzk avatar Dec 06 '22 08:12 raddatzk

Thanks for the sample.

When you're using @SpringBootTest and, therefore, full auto-configuration, Spring Boot's default AOP configuration is used and this results in the use of class- rather than interface-based proxies. As a result, the annotations on PeopleController are found.

When you're using @WebMvcTest, AopAutoConfiguration isn't included and interface-based proxies are used instead. You can work around this by importing the auto-configuration in your test:

@WebMvcTest(PeopleController.class)
@Import(SecurityConfig.class)
@ImportAutoConfiguration(AopAutoConfiguration.class)
public class PeopleControllerTest {

I'd like to discuss the need for this with the rest of the team. Ideally, it wouldn't be needed but I am not sure that we should include AopAutoConfiguration in @WebMvcTest by default as it may have some side-effects that aren't wanted by those for whom things are working fine at the moment.

wilkinsona avatar Jan 17 '23 11:01 wilkinsona

I've recently encountered this issue, and found this after some search.

It will be nice if this is being mentioned in the docs under @WebMvcTest portion

bwgjoseph avatar May 04 '23 10:05 bwgjoseph

When looking at this, we may need to revisit PropertyPlaceholderAutoConfiguration as well as it should probably be available by default too.

snicoll avatar Sep 11 '23 15:09 snicoll