title: How test an @RequestScope component with WireMockServer? Gets error "java.lang.IllegalStateException: No thread-bound request found..."
body: <p>I have an <code>@RequestScope</code> component and I'm trying to test it with wire mock server, but it throws the exception:</p>
  
  <blockquote>
    <p>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/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.</p>
  </blockquote>
  
  <p>The class is:</p>
  
  <pre><code>@Component
  @RequestScope
  public class MyData
  {
      private static final Logger LOGGER = LoggerFactory.getLogger( MyData.class );
  
      @Autowired
      private MyData MyData;
  
      public MyData()
      {
      }
  
      //...elided...
  }
  </code></pre>
  
  <p>And the test:</p>
  
  <pre><code>@RunWith( SpringJUnit4ClassRunner.class )
  @SpringBootTest(
      webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
  )
  @ActiveProfiles( { "test-My-data" } )
  @TestPropertySource(
      properties = {
          "BASE_URL_PROTOCOL=http",
          "BASE_URL=localhost"
      }
  )
  public class MyDataIntegrationTest
  {
      @Value( "${BASE_URL_PROTOCOL}" )
      private String baseProtocol;
  
      @Value( "${BASE_URL}" )
      private String baseUrl;
  
      @Autowired
      Provider&lt;MyData&gt; MyData;
  
      private WireMockServer wireMockServer;
  
      @Before
      public void setUp()
      {
          // WireMock configuration.
          wireMockServer = new WireMockServer( options().dynamicPort() );
          wireMockServer.start();
      }
  
      @Test
      public void testMyData()
      {
          wireMockServer.stubFor(
              WireMock.get(
                  urlEqualTo(
                      String.format(
                          "/my-svc/%s/data", "user1"
                      )
                  )
              ).willReturn(
                  aResponse().withBody(
                      "{\"department\": \"one\", " +
                      "\"position\": \"teacher\" }"
                  ).withHeader( "Content-Type", "application/json" ) 
              )
          );
  
          String userName = MyData.get().getUserName( "user1" );
  
          wireMockServer.verify( 1, getRequestedFor( urlEqualTo( String.format( "/my-svc/%s/data", "user1" ) ) ) );
  
          assertThat( userName, equalTo( "Joe Doe" ) );
      }
  }
  </code></pre>