Keep session in subsequent Java calls to Play 2.0's fakeRequest

送分小仙女□ 提交于 2019-12-05 11:34:42
Arjan

Not much magic needed after all. The following simply preserves the HTTP header that sets the cookies, and passes that in the next request:

Map<String, String> data = new HashMap<String, String>();
data.put("email", "guillaume@sample.com");
data.put("password", "secret");

Result result = callAction(controllers.routes.ref.Application.authenticate(),
  fakeRequest().withFormUrlEncodedBody(data));

assertThat(status(result)).isEqualTo(Status.SEE_OTHER);
assertThat(redirectLocation(result)).isEqualTo("/");
// All fine; we're logged in. Preserve the cookies:
String cookies = header(HeaderNames.SET_COOKIE, result);

// Fetch next page, passing the cookies
result = routeAndCall(fakeRequest(GET, redirectLocation(result))
  .withHeader(HeaderNames.COOKIE, cookies));

assertThat(status(result)).isEqualTo(Status.OK);
assertThat(contentAsString(result).contains("Guillaume Bort"));

(See the first version of this very answer for some information about getting only the PLAY_SESSION cookie, and parsing that. That's hardly needed though.)

It's really easy with the current version of Play to use the session in your tests. You can use the cookies(Result result) static helper method.

// Route that sets some session data to be used in subsequent requests
Result result = callAction(...);
Http.Cookie[] cookies = FluentIterable.from(cookies(result)).toArray(Http.Cookie.class);

FakeRequest request = new FakeRequest(GET, "/someRoute").withCookies(cookies);
callAction(controllers.routes.ref.Application.requestNeedingSession(), request);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!