伪造 Ajax 测试申请表
Faking Ajax Request Form for testing
在我的 Playframework 2.4 项目中,我有这样的方法:
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");
}
我想为这些方法编写 JUnit 测试,运行 解决我不知道如何重新创建通常会在我的应用程序中调用这些方法的 Ajax 请求的问题。
我正在寻找一种伪造 ajax 请求并将所需字段集成到请求中的方法,以便我可以成功测试这些方法。
您可以使用 FakeRequest
传递给 route()
调用。
@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());
}
详情请看游戏文档Testing your application > Unit testing controllers and Writing functional tests > Testing the router章节。
在我的 Playframework 2.4 项目中,我有这样的方法:
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");
}
我想为这些方法编写 JUnit 测试,运行 解决我不知道如何重新创建通常会在我的应用程序中调用这些方法的 Ajax 请求的问题。
我正在寻找一种伪造 ajax 请求并将所需字段集成到请求中的方法,以便我可以成功测试这些方法。
您可以使用 FakeRequest
传递给 route()
调用。
@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());
}
详情请看游戏文档Testing your application > Unit testing controllers and Writing functional tests > Testing the router章节。