MVC .NET单元测试:如何测试参数从控制器发送到视图

时间:2012-05-15 13:21:05

标签: asp.net-mvc-3 unit-testing mstest controllers

我是MVC .NET的新手(我之前曾在Ruby On Rails上工作)。

我想知道如何编写单元测试来检查正确的参数是否传递到视图中。

public ActionResult Users()
{
  var users = userManager.GetUsers();
  return View(users);
}

如何测试View已与用户列表一起传递?我只是模拟View静态方法还是有更好的方法?

谢谢!

1 个答案:

答案 0 :(得分:6)

您应该模拟userManager.GetUsers方法,然后断言控制器操作返回的ViewResult模型等于模拟的用户列表。当然,为了能够模拟userManager.GetUsers方法,这个方法需要是虚拟的:

例如:

public class HomeController: Controller
{
    private readonly IUsersManager _usersManager;
    public HomeController(IUsersManager usersManager)
    {
        _usersManager = usersManager;
    }

    public ActionResult Users()
    {
        var users = _usersManager.GetUsers();
        return View(users);
    }    
}

现在,在单元测试中,您可以提供IUsersManager接口的模拟实例,并定义GetUsers方法的期望。

使用诸如Rhino Mocks之类的模拟框架这是一项微不足道的任务:

[TestMethod]
public void Users_Action_Should_Query_The_UserManager_Repository_And_Pass_The_Result_To_The_View()
{
    // arrange
    var expectedUsers = new User[] { new User() };
    var usersManagerStub = MockRepository.GenerateStub<IUsersManager>();
    usersManagerStub.Stub(x => x.GetUsers()).Return(expectedUsers);
    var sut = new HomeController(usersManagerStub);

    // act
    var actual = sut.Users();

    // assert
    Assert.IsInstanceOfType(actual, typeof(ViewResult));
    var viewResult = actual as ViewResult;
    Assert.AreEqual(expectedUsers, viewResult.Model);
}

并使用MVCContrib.TestHelper它为您提供了更流畅的语法,简化了标准HTTP工件的模拟,例如上下文,会话,cookie,......:

[TestMethod]
public void Users_Action_Should_Query_The_UserManager_Repository_And_Pass_The_Result_To_The_View()
{
    // arrange
    var expectedUsers = new User[] { new User() };
    var usersManagerStub = MockRepository.GenerateStub<IUsersManager>();
    usersManagerStub.Stub(x => x.GetUsers()).Return(expectedUsers);
    var sut = new HomeController(usersManagerStub);

    // act
    var actual = sut.Users();

    // assert
    actual
        .AssertViewRendered()
        .WithViewData<User[]>()
        .ShouldEqual(expectedUsers, "");
}