Faking Ajax Request Form for testing

490 views Asked by At

In my Playframework 2.4 project I have methods like this:

public static Result resetValue(int client) {
    String receivedName= form().bindFromRequest().get("username");
    User user = User.findByName(receivedName);
    if( user == null ) {
        return badRequest("No user logged in");
    }
    user.setValue(0);
    user.saveUsertoDB();
    return ok("Value set to zero");
}

I want to write JUnit Tests for those methods and ran into the problem that I don`t know how to recreate the Ajax Requests which would normally call those methods in my application.

I am looking for a way to fake the ajax requests and integrate the needed fields into the request so that I can successfully test those methods.

1

There are 1 answers

0
Alexander B On BEST ANSWER

You can use a FakeRequest to be passed to a route()-call.

@Test
public void testResetValueWithFakeRequest() {
    Call call = controllers.routes.Application.resetValue(1);
    ImmutableMap<String, String> formData = ImmutableMap.of("username", "Jakob");
    RequestBuilder request = fakeRequest(call).bodyForm(formData);
    Result result = route(request);
    assertEquals(OK, result.status());
}

Please see chapters Testing your application > Unit testing controllers and Writing functional tests > Testing the router in play documentation for details.