需求和问题

Given a simple action:【简单给一个action如下：】

:::java
public static void testAction() {
session.put("worked", "yes");
}


I want to test that the session is set:【我试着测试这个session是否被设置：】

:::java
@Test
public void setsTheSession() {
Response response = GET("/test");
assertEquals("yes", Scope.Session.current().get("worked"));
}


But Scope.Session.current() always returns an empty map. Any clues?
【但Scope.Session.current()总是返回一个空的Map。有什么办法吗？】

关键回答

I don’t think that works because you are not in the context of a server request when in a test. You are just acting as a regular browser making a GET request.
【我不认为可以那样写，因为在一个test中你不在服务请求的上下文中。你只是象一个普通的浏览器那样发送了一个GET请求。】
If you want to set a cookie from a Controller you do this:
response.setCookie("mycookie", "myvalue", "1d");{java} Then in your test you can do:
【然后在你的测试中，你可以这样：】

:::java


For sessions you should take a look at this first:
【而session方面，你就应该先看一下这个：】
http://www.playframework.org/documentation/1.2.3/controllers#session

“It’s important to understand that Session and Flash data are not stored in the server but are added to each subsequent HTTP Request, using the Cookie mechanism. So the data size is very limited (up to 4 KB) and you can only store String values.”
They are of course signed so they can’t be changed. If I write session.put(“testcookie”, “brian”) I get this in the response header:
"PLAY_SESSION=31a4e4777b5950d78b9f3f88b02dfdb2361b5699-%00testcookie%3Abrian%00;Path=/"

This makes the job of testing actual session variables a little harder. I haven’t seen anything in the test code that does this for you. You have to go back to the play code to decode the session cookie to check for what you originally wanted to do. The function in playframework\framework\src\play\mvc\Scope.java restore() isn’t accessible so it looks like you have to either use reflection of some sort to call it or write your own session parse function like this (uses the secret from the application.conf to decode):
https://gist.github.com/1224015

Then you can assert your session code pretty much as you were doing:
【然后你就可以用类似下面的办法校验你的session值了：】

:::java
@Test
public void setsTheSession() throws UnsupportedEncodingException
{