在每个单元测试之前创建会话

时间:2013-07-05 12:20:21

标签: java junit playframework playframework-2.1

我想用Play 2.1.1驱动单元测试,这取决于用户是否已登录或通过API密钥进行身份验证。我想做这样的事情:

/**
 * Login a user by app, email and password.
 */
@Before
public void setSession() {
    session("app", "app")
    session("user", "user0@company.co")
    session("user_role", "user");
}

有人能指出我正确的方法还是有另一种方法可以让我将登录功能与单一单元测试分开?提前谢谢!

1 个答案:

答案 0 :(得分:2)

由于在Playframework中,Servlet API(Playframework uses cookies)中没有服务器端会话,因此您必须为每个请求模拟会话。

您可以尝试使用FakeRequest.withSession()

private FakeRequest fakeRequestWithSession(String method, String uri) {
    return play.test.Helpers.fakeRequest(method, uri).withSession("app", "app").withSession("user", "user0@company.co").withSession("user_role", "user");
}

@Test
public void badRoute() {
  Result result = routeAndCall(fakeRequestWithSession(GET, "/xx/Kiki"));
  assertThat(result).isNull();
}