【问题标题】:Testing controller action for expected rendered view in Playframework 2.1在 Playframework 2.1 中测试预期渲染视图的控制器操作
【发布时间】:2013-07-17 00:34:29
【问题描述】:

在 playframework 2.1 中,是否可以测试一个动作以确保呈现的视图是我所期望的?

在 ASP.NET MVC 3 中,AssertViewRendered().ForView("view") 进行了准确的测试。我们可以在play 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");
}

谢谢。

【问题讨论】:

    标签: java unit-testing playframework-2.1


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 感谢 nico_ekito 的回答,我知道要测试视图的内容,但这不是我在这种情况下需要的。我编辑了我的帖子改进了这个例子,希望它能澄清一点:)
      • 由于调用的视图是一个方法,所以很难判断调用的是哪个方法。也许通过使用模拟框架来验证某些行为 (mockito.googlecode.com/svn/branches/1.8.0/javadoc/org/mockito/…)。
      猜你喜欢
      • 1970-01-01
      • 2015-10-29
      • 1970-01-01
      • 2015-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多