23.4.6. Testing resources and providers
Seam includes a unit testing utility class that helps you create unit tests for a RESTful architecture. Extend the
SeamTest
class as usual and use the ResourceRequestEnvironment.ResourceRequest
to emulate HTTP requests/response cycles:
import org.jboss.seam.mock.ResourceRequestEnvironment; import org.jboss.seam.mock.EnhancedMockHttpServletRequest; import org.jboss.seam.mock.EnhancedMockHttpServletResponse; import static org.jboss.seam.mock.ResourceRequestEnvironment.ResourceRequest; import static org.jboss.seam.mock.ResourceRequestEnvironment.Method; public class MyTest extends SeamTest { ResourceRequestEnvironment sharedEnvironment; @BeforeClass public void prepareSharedEnvironment() throws Exception { sharedEnvironment = new ResourceRequestEnvironment(this) { @Override public Map<String, Object> getDefaultHeaders() { return new HashMap<String, Object>() {{ put("Accept", "text/plain"); }}; } }; } @Test public void test() throws Exception { //Not shared: new ResourceRequest(new ResourceRequestEnvironment(this), Method.GET, "/my/relative/uri) new ResourceRequest(sharedEnvironment, Method.GET, "/my/relative/uri) { @Override protected void prepareRequest(EnhancedMockHttpServletRequest request) { request.addQueryParameter("foo", "123"); request.addHeader("Accept-Language", "en_US, de"); } @Override protected void onResponse(EnhancedMockHttpServletResponse response) { assert response.getStatus() == 200; assert response.getContentAsString().equals("foobar"); } }.run(); } }
This test only executes local calls, it does not communicate with the
SeamResourceServlet
through TCP. The mock request is passed through the Seam servlet and filters and the response is then available for test assertions. Overriding the getDefaultHeaders()
method in a shared instance of ResourceRequestEnvironment
allows you to set request headers for every test method in the test class.
Note that a
ResourceRequest
has to be executed in a @Test
method or in a @BeforeMethod
callback. You can not execute it in any other callback, such as @BeforeClass
.