Ajax request form fake for testing

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 these methods, and I am faced with the problem that I do not know how to recreate the Ajax requests that these methods usually called in my application.

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

+4
source share
1 answer

You can use FakeRequestto transfer to 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());
}

. > > .

+1

All Articles