Testing controller with fake session

為{幸葍}努か 提交于 2019-12-07 03:54:00

问题


I want to write test for my controller:

Result changeAction = callAction(controllers.routes.ref.Users.changePassword());
assertThat(status(changeAction)).isEqualTo(OK);

I have a http status code - 300.

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()));
    }


}

And when I use the @Security.Authenticated(Secured.class) annotation for controller method it redirects if session with "userId" do not exists.

So the question is, how can I fake the session?

I tried obviously call Controller.session("usderId", "2");

And got an exception:

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?

And one additional question: how to test routes without using deprecated API, like Result result = routeAndCall(fakeRequest(GET, "/change_password")); ?


回答1:


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));
       }
   });
}

Note also that I used the route method and not routeAndCall, the first is the replacement of the deprecated method.



来源:https://stackoverflow.com/questions/17007522/testing-controller-with-fake-session

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!