2013-07-17 25 views
1

在playframework 2.1中,是否可以測試操作以確保呈現的視圖是我期待的視圖?測試控制器對Playframework 2.1中的預期渲染視圖的操作

在ASP.NET MVC 3中,AssertViewRendered().ForView("view")測試的確如此。我們能玩2.1嗎?怎麼樣?

的,我想達到什麼樣的非常基本的MVC 3例子:

// Given the action GetUsers that renders the view "Users", I would like to assert 
// this view as the one I expect and no other. 
public class UserController 
{ 
    public ActionResult Index() { 
     return View("Users"); 
    } 
} 

[Test] 
public void GetUsersRendersCorrectView() 
{ 
    // Setup 
    var userService = new Mock<UserService>(); 
    var userController = new UserController(userService.Object); 

    // Excercise 
    var result = userController.GetUsers(); 

    // Verify 
    result.AssertViewRendered().ForView("Users"); 
} 

感謝。

回答

1

在播放的視圖呈現僅僅是一個方法調用(模板被編譯成簡單的Scala函數)。

沒有什麼能阻止你用「手動構建」功能實現視圖渲染。

因此,由Action返回的Result不知道內容是來自模板還是其他任何內容。這就是爲什麼你想要達到的那種斷言在Play中是不可能的。

0

不確定要完全理解,但我認爲你可以通過聲明呈現的視圖包含一些預期的數據來測試你的控制器和渲染的視圖。

Playframework documentation

@Test 
public void callIndex() { 
    Result result = callAction(
     controllers.routes.ref.Application.index("Kiki") 
    ); 
    assertThat(status(result)).isEqualTo(OK); 
    assertThat(contentType(result)).isEqualTo("text/html"); 
    assertThat(charset(result)).isEqualTo("utf-8"); 
    assertThat(contentAsString(result)).contains("Hello Kitty"); 
} 
+0

感謝nico_ekito給你回答,我意識到測試視圖的內容,但那不是我在這種情況下需要的。我編輯了我的帖子,改進了這個例子,希望它能澄清一下:) – Franco

+1

由於被調用的視圖是一個方法,因此很難判斷哪個方法被調用。也許通過使用模擬框架來驗證一些行爲(http://mockito.googlecode.com/svn/branches/1.8.0/javadoc/org/mockito/Mockito.html#1)。 –

相關問題