Today I wanted to write a functional test for a Play 1.2.4 app that required the request to come with a preinitialised Play session. At first I thought that this would be easy, however it turned out that there isn’t a ready-made solution for this built in so I had to cobble together the pieces myself.

Here is the method which I have put in the base class for all my FunctionalTests:

Http.Request sessionedRequest(Map<String, Object> data) throws Throwable{
    // mostly copied from
    StringBuilder session = new StringBuilder();
    for (String key : data.keySet()) {
    String sessionData = URLEncoder.encode(session.toString(), "utf-8");
    String sign = Crypto.sign(sessionData, Play.secretKey.getBytes());
    Http.Request req = newRequest();
    Http.Cookie cookie = new Http.Cookie();
    String cookieName = "PLAY_SESSION"; = cookieName;
    cookie.value = sign + "-" + sessionData;
    req.cookies = ImmutableMap.of(cookieName, cookie);
    return req;