Question

Here is a method that returns a view model with user information:

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

How can I unit test it using Moles framework? There is a method MMembership.CreateUserStringString() but I couldn't figure out how to implement it to fake user identity.

Was it helpful?

Solution

Ok, so I've found a solution. I had to add moles assembly for System.Web.ApplicationServices to be able to mock MembershipUser. The final test method loks like this:

    [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);
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top