1

I have an @RequestScope component and I'm trying to test it with wire mock server, but it throws the exception:

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.

The class is:

@Component
@RequestScope
public class MyData
{
    private static final Logger LOGGER = LoggerFactory.getLogger( MyData.class );

    @Autowired
    private MyData MyData;

    public MyData()
    {
    }

    //...elided...
}

And the test:

@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<MyData> 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" ) );
    }
}
2
  • Why are you autowiring in Provider<MyData> instead of MyData? May 9, 2018 at 10:01
  • @SamBrannen because it's request scoped. if you try to autowire the bean, it will fall on startup with the error, "no thread bound request found"
    – Don Rhummy
    May 10, 2018 at 1:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.