1

In playframework 2.1, is it possible to test an action to make sure the rendered view is the one I'm expecting for?

In ASP.NET MVC 3, AssertViewRendered().ForView("view") tests exactly that. Can we do it in play 2.1? How?

Very basic MVC 3 example of what I would like to achieve:

// 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");
}

Thanks.

4

2 回答 2

1

Play 中的视图渲染只是一个方法调用(模板被编译为简单的 Scala 函数)。

没有什么能阻止您使用“手动构建”功能实现视图渲染。

因此,ResultAction 返回的内容不知道是来自模板还是其他任何内容。这就是为什么 Play 无法实现您想要实现的那种断言。

于 2013-07-18T06:54:08.323 回答
0

不确定是否完全理解,但我认为您可以通过断言渲染视图包含一些预期数据来测试您的控制器和渲染视图。

Playframework 文档

@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");
}
于 2013-07-17T07:17:36.390 回答