0

这是一个返回带有用户信息的视图模型的方法:

    public ActionResult EditUserInfo(string userName)
    {
        try
        {
            var user = Membership.GetUser(userName);
            var model = new UserEditorViewModel
                            {
                                UserName = userName,
                                EmailAddress = user.Email
                            };
            return View(model);
        }
        catch
        {
            return View("Error");
        }
    }

如何使用 Moles 框架对其进行单元测试?有一种方法MMembership.CreateUserStringString(),但我不知道如何实现它来伪造用户身份。

4

1 回答 1

0

好的,所以我找到了解决方案。我必须添加痣组件System.Web.ApplicationServices才能模拟MembershipUser。最终的测试方法如下所示:

    [TestMethod, HostType("Moles")]
    public void EditUserInfoTest()
    {  
        var testUserName = "TestUser";
        var controller = new UserEditorController();
        using (MolesContext.Create())
        {
            var user = new MMembershipUser
            {
                UserNameGet = () => "TestUser",
                EmailGet = () => "test@test.test"
            };        
            MMembership.GetUserString = (userName) =>
            {
                Assert.AreEqual(testUserName, userName);
                return user;
            };
            var result = (ViewResult)controller.Edit(testUserName);                
            Assert.AreNotEqual("Error", result.ViewName);
        }
    }
于 2012-07-16T22:20:56.187 回答