Spring Boot 2.4.2

Having a @RequestScope bean autowired inside the controller, the following test fails:

@SpringBootTest
@AutoConfigureMockMvc
public class ControllerTest {
    @Autowired MockMvc mockMvc;

    @Test
    public void testGet() throws Exception {
        mockMvc.perform( get( "/somepath" ) )
                .andExpect( status().isOk() );
    }
}

org.springframework.beans.factory.support.ScopeNotActiveException: Error creating bean with name 'scopedTarget.myRequestScopeBean': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

Searching docs, the only related content I've found is testcontext-web-scoped-beans that doesn't apply to mockmvc.

Comment From: cdalexndr

It seems that the problem is somewhere in these lines: https://github.com/spring-projects/spring-boot/blob/72a1eb6384bc5ca9171e0433dc6a3bb750c8e8b0/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfiguration.java#L75-L78

The following works:

@SpringBootTest
@AutoConfigureMockMvc
public class ControllerTest {
    @Autowired MockMvc mockMvc;
    @Autowired WebApplicationContext webApp;

    @Test
    public void testGet() throws Exception {
         MockMvcBuilders.webAppContextSetup( webApp )
                .build().perform( get( "/somepath" ) )
                .andExpect( status().isOk() );
    }
}

Comment From: wilkinsona

This works for me. The request context is set by ServletTestExecutionListener as it should be. I would guess that's not happening for you for some reason. It's impossible to say for certain why it's not happening but, judging by previous issues that you have raised, I would guess that could be because you're using TestNG where the test execution listeners must be configured manually. If that's not the case and you would like us to spend some more time investigating, please spend some time providing a complete yet minimal sample that reproduces the problem. You can share it with us by pushing it to a separate repository on GitHub or by zipping it up and attaching it to this issue.