Search code examples
exceptionplayframeworkfunctional-testing

Unexpected error using newRequest in FunctionalTests


I don't understand why I have this error. When I use newRequest, I have a RuntimeException when calling the makeRequest(request); method.

The exception message is : "play.mvc.results.NotFound : POST /" But what is odd, is that in the .url, I specify "/dashboard", not "/" (and of course, the url is well indicated in the routes file for POST requests!)

Thanks for your help.

Here is my test class :

public class DashboardTest extends FunctionalTest {
    protected Request ajaxRequest;

    @Before
    public void _setUp() {
        Fixtures.deleteDatabase();
        Fixtures.loadModels("fixtures/accounts.yml");

        ajaxRequest = newRequest();
        //ajaxRequest.headers.put("X-Requested-With", new Header("X-
Requested-With", "XMLHttpRequest"));
        ajaxRequest.method = "POST";
        ajaxRequest.url = "/dashboard";
    }

    @Test
    public void testAuthenticateWithValidDataAjax() {
        ajaxRequest.params.put("email", "[email protected]");

        Response response = makeRequest(ajaxRequest);
        assertIsOk(response);
        assertContentType("application/json", response);
    }
}

Solution

  • Looking at the API documentation, the .url specifies that it needs the Full URL. What I would suggest you do instead, is to use the .action instead.

    The Javadoc for the this is

    Full action (ex: Application.index)

    or specify the full URL, which would include

    http://localhost:9000/dashboard
    

    Your final option, if you are still having problems, is to use the createRequest method on the Http.Request object, which gives you complete control over the Request object you are creating. The signature looks like this

    createRequest
    
    public static Http.Request createRequest(java.lang.String _remoteAddress,
                                             java.lang.String _method,
                                             java.lang.String _path,
                                             java.lang.String _querystring,
                                             java.lang.String _contentType,
                                             java.io.InputStream _body,
                                             java.lang.String _url,
                                             java.lang.String _host,
                                             boolean _isLoopback,
                                             int _port,
                                             java.lang.String _domain,
                                             boolean _secure,
                                             java.util.Map<java.lang.String,Http.Header> _headers,
                                             java.util.Map<java.lang.String,Http.Cookie> _cookies)