用假会话测试控制器 [英] Testing controller with fake session
问题描述
我想为我的控制器编写测试:
Result changeAction = callAction(controllers.routes.ref.Users.changePassword());
assertThat(status(changeAction)).isEqualTo(OK);
我有一个http状态码-300.
I have a http status code - 300.
是的,它是重定向的,因为我有一个名为Secured的类
That's right it is redirect because I have a class named Secured
package controllers;
import play.mvc.*;
import play.mvc.Http.*;
public class Secured extends Security.Authenticator {
@Override
public String getUsername(Context ctx) {
return ctx.session().get("userId");
}
@Override
public Result onUnauthorized(Context ctx) {
return redirect(routes.Users.login(ctx.request().uri()));
}
}
当我将@Security.Authenticated(Secured.class)
注释用于控制器方法时,如果与"userId"的会话不存在,它将重定向.
And when I use the @Security.Authenticated(Secured.class)
annotation for controller method it redirects if session with "userId" do not exists.
所以问题是,我该如何伪造会话?
我试图打给Controller.session("usderId", "2");
有一个例外:
java.lang.RuntimeException: There is no HTTP Context available from here.
at play.mvc.Http$Context.current(Http.java:30)
at play.mvc.Controller.session(Controller.java:54)
at play.mvc.Controller.session(Controller.java:61)
at controllers.UsersTest.testUnloginedChangePassword(UsersTest.java:35)
我的问题是:如何为控制器伪造会话?
My question is: How to fake the session for controller?
还有一个问题:如何在不使用不推荐使用的API的情况下测试路由,例如Result result = routeAndCall(fakeRequest(GET, "/change_password"));
?
And one additional question: how to test routes without using deprecated API, like Result result = routeAndCall(fakeRequest(GET, "/change_password"));
?
推荐答案
您可以使用fakeRequest
的withSession(String, String)
方法将内容放入会话中.请注意,这将返回fakeRequest
,因此,如果需要在会话中放置多个键,则可以链接该方法.
You can use the withSession(String, String)
method of fakeRequest
to put things in the Session. Note that this returns a fakeRequest
so you can chain that method if you need to put multiple keys in the session.
然后您的测试可能看起来像这样:
Your test could then look something like this:
@Test
public void test() {
running(fakeApplication(), new Runnable() {
public void run() {
String username = "Aerus";
Result res = route(fakeRequest("GET", "/")
.withSession("username", username)
.withSession("key","value"));
assert(contentAsString(res).contains(username));
}
});
}
还请注意,我使用的是route
方法,而不是routeAndCall
,首先是替换不推荐使用的方法.
Note also that I used the route
method and not routeAndCall
, the first is the replacement of the deprecated method.
这篇关于用假会话测试控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!