2016-04-15 25 views
1

這裏簡單的播放渲染視圖測試。在視圖模板中,我試圖通過flash.get()訪問會話信息。 但測試失敗,並顯示消息There is no HTTP Context available from here.如何在junit測試環境中將假會話數據添加到測試應用程序中?玩2.5渲染視圖測試,獲取flash消息

public class ApplicationTest extends WithServer { 

private FormFactory formFactory() { 
    return app.injector().instanceOf(FormFactory.class); 
} 

@Test 
public void renderTemplate() { 
    Content html; 
    session().put("session","123"); 
    html = index.render(formFactory().form(Auth.Login.class)); 
    assertTrue(contentAsString(html).contains("Hello")); 
} 

}

Test ApplicationTest.renderTemplate failed: java.lang.RuntimeException: There is no HTTP Context available from here., took 0.544 sec 
at play.mvc.Http$Context.current(Http.java:57) 
at play.mvc.Http$Context$Implicit.flash(Http.java:307) 
at views.html.index_Scope0$index$$anonfun$apply$1.apply(index.template.scala:39) 
at views.html.index_Scope0$index$$anonfun$apply$1.apply(index.template.scala:38) 
at views.html.helper.form_Scope0$form.apply(form.template.scala:35) 
at views.html.index_Scope0$index.apply(index.template.scala:38) 
at views.html.index_Scope0$index.render(index.template.scala:141) 
at views.html.index.render(index.template.scala) 
at ApplicationTest.renderTemplate(ApplicationTest.java:37) 

回答

1

使用WithServer啓動一個應用程序,你可以請求。對於這裏描述的測試,您需要使用WithApplication

要手動設置上下文,可以覆蓋startPlay方法。

@Override 
public void startPlay() 
{ 
    super.startPlay(); 
    Http.Context.current.set(new Http.Context(1L, 
               Mockito.mock(RequestHeader.class), 
               Mockito.mock(Http.Request.class), 
               Collections.<String, String>emptyMap(), 
               Collections.<String, String>emptyMap(), 
               Collections.<String, Object>emptyMap())); 
}