2014-04-01 48 views
2

在最新的documentation中,以模板測試爲例。PlayFramework 2模板測試

@Test 
public void renderTemplate() { 
    Content html = views.html.index.render("Coco"); 
    assertThat(contentType(html)).isEqualTo("text/html"); 
    assertThat(contentAsString(html)).contains("Coco"); 
} 

但我該如何運行?我嘗試了它自己,在一個假的服務器上的run()方法,一個真正的服務器,一邊實際運行的服務器,我總是得到這個錯誤。

[error] Test ApplicationTest.testInServer failed: java.lang.RuntimeException: There is no HTTP Context available from here. 

在文檔中測試的字面上有兩個頁面,我不知道如何實際運行這些測試。是否有一個示例類沒有使用棄用的方法(自Play 1以來事情已發生變化,大多數情況都不再起作用)。

回答

0

從命令行運行「play test」。這將運行測試文件夾中的所有測試。

+0

這就是我如何運行測試,有我複製到我的職位的錯誤。 – user2787904

3

您需要設置HTTP上下文第一。

與實例的Mockito:

@Test 
public void indexTest() { 
    //setup HTTP Context 
    Http.Context context = Mockito.mock(Http.Context.class); 
    //mocking flash session, request, etc... as required 
    Http.Flash flash = Mockito.mock(Http.Flash.class); 
    when(context.flash()).thenReturn(flash); 
    Http.Context.current.set(context); 

    //run your test 
    Content html = views.html.index.render("Coco"); 
    assertThat(contentType(html)).isEqualTo("text/html"); 
    assertThat(contentAsString(html)).contains("Coco"); 
}