所以,在 Play 中进行测试让我很头疼,我希望有人能够解答我的问题。
我需要测试我的注册系统(以及许多其他事情),这当然涉及代表用户提交表单。
我的 Controller 操作的精简版本 - add()
public static Result add() {
String email = form().bindFromRequest().get("email");
String name = form().bindFromRequest().get("name");
String password = form().bindFromRequest().get("password");
String password_confirm = form().bindFromRequest().get("password-confirm");
[stripped out code]
if(!check){
flash("error", "Not a valid email, please use the email address provided by your employer");
return redirect(
routes.UserController.registration()
);
}
else {
String passwordHash = BCrypt.hashpw(form().bindFromRequest().get("password"), BCrypt.gensalt());
// Create unverified User
User newUser = User.create(
form().bindFromRequest().get("email"),
form().bindFromRequest().get("name"),
passwordHash
);
// Generate verification key
String key = newUser.verification_key;
// Send verification email
sendVerificationLink(key);
flash("success", "Thanks for registering! We have sent you an email with a verification link.");
return redirect(
routes.Application.login()
);
}
这是我编写的 JUnit 测试。
@Test
public void registerTest() {
running(fakeApplication(), new Runnable() {
public void run() {
String registeredUserName = "bob";
String registeredUserEmail = "bob@gmail.ac.uk";
String registeredUserPass = "secret";
String registeredUserPassConfirm = "secret";
Map<String, String> userData = new HashMap<String, String>();
userData.put("name", registeredUserName);
userData.put("email", registeredUserEmail);
userData.put("password", registeredUserPass);
userData.put("passwordconfirm", registeredUserPassConfirm);
Result r = callAction(routes.ref.UserController.add(), fakeRequest()
.withFormUrlEncodedBody(Form.form(User.class).bind(userData).data()));
assertEquals(r, 200);
}
});
}
在 HashMap 中给出适当正确的详细信息,在我看来,r 应该返回 OK 或 200?
但是,我收到以下信息...“预期:play.test.Helpers$1@29cd761a,但实际是:<200>”
这个“play.test.Helpers$1@29cd761a”是什么?看起来它引用了一个对象或内存地址,但我不知道为什么??
如果这无论如何都含糊不清,请直接说出来,我会尽力详细说明。
提前致谢
最佳答案
哟!
成功了!
对于其他暂时脑放屁的人...使用 status() 方法读取返回的结果!
Result r = callAction(routes.ref.UserController.add(), fakeRequest()
.withFormUrlEncodedBody(Form.form(User.class).bind(userData).data()));
assertEquals(200, status(r));
关于java - 使用 Java 和 JUnit 在 Play 2 中测试表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23244086/