在Play Framework 2.1中测试预期渲染视图的控制器操作

时间:2013-07-17 00:34:30

标签: java unit-testing 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");
}

感谢。

2 个答案:

答案 0 :(得分:1)

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

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

因此,Action返回的Result不知道内容是来自模板还是其他任何内容。这就是为什么Play无法实现你想要达到的断言的原因。

答案 1 :(得分: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");
}