Description
Describe the bug
In a Spring Boot application with multiple servlets registered to the context (DispatcherServlet and at least one other), an IllegalArgumentException
with message Failed to find servlet [] in the servlet context
is thrown when running tests with MockMvc
and @SpringBootTest(webEnvironment = RANDOM_PORT)
.
The problem started occurring after an upgrade from Spring Boot 3.0.2 to Spring Boot 3.2.1 (Spring Security 6.2.1).
The exception is thrown in the DispatcherServletDelegatingRequestMatcher due to an incompatibility with the standard MockHttpServletRequest instances created with the MockMvcRequestBuilders class. These have a generic HttpRequestMapping with an empty String as the servletName, thus causing the Matcher to not find a ServletRegistration and throw the exception.
Gist with full stacktrace: Gist
To Reproduce
Run the tests in the provided sample to reproduce.
In the sample is a simple Spring Boot app with an extra servlet registered to the context and a basic security setup.
The included tests demonstrate 2 working cases and one failing case.
The test TestWithRandomPortEnvironment#expected_failure demonstrates the exception.
TestWithRandomPortEnvironment#expected_success demonstrates the fix I implemented to make this work with a RequestPostProcessor, but this solution would have to be applied everywhere I'm using MockMvc.
Expected behavior
The DispatcherServletDelegatingRequestMatcher should be compatible with the standard MockHttpServletRequest instances created with the MockMvcHttpRequestBuilders and not throw an exception.
Sample
Sample repository