spring-projects / spring-boot

Spring Boot
https://spring.io/projects/spring-boot
Apache License 2.0
74.95k stars 40.65k forks source link

Enable AopAutoConfiguration by default for slice tests #33415

Open raddatzk opened 1 year ago

raddatzk commented 1 year ago

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

wilkinsona commented 1 year ago

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

raddatzk commented 1 year ago

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

The ApplicationTest succeeds while PeopleControllerTest fails with 404

wilkinsona commented 1 year ago

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.

bwgjoseph commented 1 year ago

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

snicoll commented 1 year ago

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