ASP.NET使用Moles框架模拟Membership.GetUser

时间:2012-07-16 17:06:55

标签: c# asp.net-mvc unit-testing moles

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

    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(),但我无法弄清楚如何实现它以伪造用户身份。

1 个答案:

答案 0 :(得分:0)

好的,所以我找到了解决方案。我必须为System.Web.ApplicationServices添加moles程序集才能模拟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);
        }
    }