Fake Session Test Controller

I want to write a test for my controller:

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

I have an http status code of 300.

This right is redirected because I have a class called 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 the controller method, it redirects if the session with "userId" does not exist.

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

I tried obviously calling 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 a session for a controller?

And one more question: how to test routes without using the outdated API, for example Result result = routeAndCall(fakeRequest(GET, "/change_password")); ?

+6
source share
1 answer

You can use the withSession(String, String) fakeRequest to put things into the session. Note that this returns fakeRequest , so you can bind this method if you need to put multiple keys in a session.

Then your test might 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)); } }); } 

Please note that I used the route method, not routeAndCall , the first is a replacement for the deprecated method.

+6
source

Source: https://habr.com/ru/post/946885/


All Articles