如何在 Play Framework 1.2.3 的功能测试中伪造会话值?
我正在做一个简单的测试,例如:
在运行测试之前,我设置了一个空白会话,希望它能够成为测试的一部分:
@Before
public void setupHTTP() {
Session.current.set(new Session());
}
@Test
public void testRedirectToUserHomeForAuthenticatedUserWhenBlankAction() {
authenticateUser("[email protected] /cdn-cgi/l/email-protection");
Response response = GET("/user/blank");
assertRedirected(response, "/user/home");
}
方法
authenticate(String userEmail)
just put the key "username" in the session map:
protected void authenticateUser(String userEmail) {
// Put in session the email
Session.current.get().put(USERNAME, userEmail);
}
但是测试在不同的线程中运行,只要我能理解,并且看不到我设置的会话......
如何在功能测试中伪造会话值?
我有同样的问题,但在 Play 2.0.4 的测试中。
我通过以下方式解决了问题Seb https://stackoverflow.com/a/8119106/1792009 and Codemwnci https://stackoverflow.com/a/5762992/1792009答案和我建立,检查 API,以下解决方案:
@Test
public void listSomething() {
running(fakeApplication(inMemoryDatabase()), new Runnable() {
@Override
public void run() {
// LOGIN
final Map<String, String> data = new HashMap<String, String>();
data.put("email", "[email protected] /cdn-cgi/l/email-protection");
data.put("password", "userpassword");
Result result = callAction(
controllers.routes.ref.Application.authenticate(),
fakeRequest().withFormUrlEncodedBody(data));
// RECOVER COOKIE FROM LOGIN RESULT
final Cookie playSession = play.test.Helpers.cookie("PLAY_SESSION",
result);
// LIST SOMETHING (using cookie of the login result)
result = callAction(controllers.routes.ref.Application.list(),
fakeRequest().withCookies(playSession));
/*
* WAS RECEIVING 'SEE_OTHER' (303)
* BEFORE RECOVERING PLAY_SESSION COOKIE (BECAUSE NOT LOGGED IN).
*
* NOW, EXPECTED 'OK'
*/
assertThat(status(result)).isEqualTo(OK);
assertThat(contentAsString(result)).contains(
"Something found");
}
});
}
Application.list() 是这样的:
@Security.Authenticated(Secured.class)
public static Result list() {
return ok(list.render(...));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)