- | rssFeed | My book on MSBuild and Team Build | Archives and Categories Friday, March 26, 2010

MOQ: Comparing hard coded mocks to moq mocks

I'm working on an application right now which uses some mock classes which were "hand written" instead of using a mock framework. I haven't had much experience with using mock frameworks, but I've wanted to learn more about them. There are many mock frameworks out there, I chose to use moq because the test cases for ASP.NET MVC use moq. What I wanted to do was replace the mock class that I created with a moq class. If you have ever created mock classes before then you probably know that they are pretty annoying to maintain. What I mean is that if you add a method/property to the interface which the mock class implements then you have to update the mock just to get it to build. This is annoying and kinda makes people not to use the mock which then ends up in ignoring/commenting out test cases. To avoid all of this most mock frameworks, including moq, just require you to specify behavior for methods/properties which you are ready to exercise in your test cases. Now I’d like to show you the mock class that I had. This interface that it is mocking is used to abstract the data store.

internal class MockModelContext :IModelContext
{
    public User CreateUser(User user)
    {
        // if id is not set, set it and just return it
        if (user.Id <= 0)
        {
            user.Id = 1;
        }

        return user;
    }

    public User GetUserByEmail(string email)
    {
        if (string.IsNullOrEmpty(email)) { throw new ArgumentNullException("email"); }

        User user = CreateDummyUser();
        user.Email = email;

        return user;
    }

    public User GetUser(Expression<Func<User, bool>> filter)
    {
        return CreateDummyUser();
    }

    public IList<Task> GetRecentTasks()
    {
        IList<Task> tasks = new List<Task>()
        {
            new Task()
            {
                CreatedDate = new DateTime(2010,1,1,1,1,1),
                CreatorId = 1,
                //Description ="Description 01 here",
                Headline="Headline 01 here",
                Id = 1,
                LastEditedDate= new DateTime(2010,1,1,1,1,1),
                LastEditOwnerId=1,
                Name = "Name here",
                NumViews = 3,
                Script = @"<ScriptHere>script</ScriptHere>",
                // TODO: Tags
                // TODO: TaskComments
                User = new User()
                {
                    Email ="one@hotmail.com",
                    FirstName="First",
                    Id=2,
                    LastName="Last",
                    MiddleName="Middle",
                }
            },
            new Task()
            {
                CreatedDate = new DateTime(2010,1,1,1,1,1),
                CreatorId = 1,
                //Description ="Description 02 here",
                Headline="Headline 02 here",
                Id = 1,
                LastEditedDate= new DateTime(2010,1,1,1,1,1),
                LastEditOwnerId=1,
                Name = "Name here",
                NumViews = 3,
                Script = @"<ScriptHere>script2</ScriptHere>",
                // TODO: Tags
                // TODO: TaskComments
                User = new User()
                {
                    Email ="one@hotmail.com",
                    FirstName="First",
                    Id=2,
                    LastName="Last",
                    MiddleName="Middle",
                }
            }
        };

        return tasks;
    }
    protected internal User CreateDummyUser()
    {
        User user = new User()
        {
            Email = "email",
            FirstName = "First",
            LastName = "Last",
            MiddleName = "Middle"
        };

        return user;
    }
    public User GetUserByOpenIdUrl(string openIdUrl)
    {
        throw new NotImplementedException();
    }
    public IList<Task> GetRecentTasks(IEnumerable<string> includeList)
    {
        throw new NotImplementedException();
    }
    public Task AddTask(Task task)
    {
        throw new NotImplementedException();
    }
    public User GetUserById(long id)
    {
        User user = this.CreateDummyUser();
        user.Id = id;

        return user;
    }
    public User SaveUser(User user)
    {
        throw new NotImplementedException();
    }
    public Task GetTaskById(long id)
    {
        throw new NotImplementedException();
    }
}

Take notice of the methods which just throw a NotImplementedException, these are methods that I just added to the interface and haven’t yet written test cases for. (Yeah I know I’m not following true TDD, but I never claimed to be either). Now you can compare that to these methods which use moq to create the mock.

private Mock<IModelContext> CreateMockModelContext()
{
    var context = new Mock<IModelContext>();

    context.Setup(c => c.CreateUser(It.IsAny<User>()))
        .Returns<User>(user =>
        {
            if (user.Id <= 0)
            {
                user.Id = 1;
            }
            return user;
        });

    context.Setup(c => c.GetUserByEmail(It.IsAny<string>()))
        .Returns<string>(email =>
            {
                if (email == null) { throw new ArgumentNullException("email"); }

                User user = this.CreateDummyUser();
                user.Email = email;

                return user;
            }); ;

    context.Setup(c => c.GetUserById(It.IsAny<long>()))
        .Returns<long>(id => 
        {
            User user = new User();
            user.Id = id;
            return user;
        });

    context.Setup(c => c.GetRecentTasks())
        .Returns(() =>
        {
            IList<Task> tasks = new List<Task>()
            {
                new Task()
                {
                    CreatedDate = new DateTime(2010,1,1,1,1,1),
                    CreatorId = 1,
                    //Description ="Description 01 here",
                    Headline="Headline 01 here",
                    Id = 1,
                    LastEditedDate= new DateTime(2010,1,1,1,1,1),
                    LastEditOwnerId=1,
                    Name = "Name here",
                    NumViews = 3,
                    Script = @"<ScriptHere>script</ScriptHere>",
                    // TODO: Tags
                    // TODO: TaskComments
                    User = new User()
                    {
                        Email ="one@hotmail.com",
                        FirstName="First",
                        Id=2,
                        LastName="Last",
                        MiddleName="Middle",
                    }
                },
                new Task()
                {
                    CreatedDate = new DateTime(2010,1,1,1,1,1),
                    CreatorId = 1,
                    //Description ="Description 02 here",
                    Headline="Headline 02 here",
                    Id = 1,
                    LastEditedDate= new DateTime(2010,1,1,1,1,1),
                    LastEditOwnerId=1,
                    Name = "Name here",
                    NumViews = 3,
                    Script = @"<ScriptHere>script2</ScriptHere>",
                    // TODO: Tags
                    // TODO: TaskComments
                    User = new User()
                    {
                        Email ="one@hotmail.com",
                        FirstName="First",
                        Id=2,
                        LastName="Last",
                        MiddleName="Middle",
                    }
                }

            };
            return tasks;
        });

    return context;
}
protected internal User CreateDummyUser()
{
    User user = new User()
    {
        Email = "email",
        FirstName = "First",
        LastName = "Last",
        MiddleName = "Middle"
    };

    return user;
}

Since I’m just mocking methods all I’m really doing here is using the moq Setup method (formerly known as Expect), and the Returns method to implement the behavior that I needed. The key to note here is that if you need to access the parameter(s) passed into the method, then you will have to used Returns and pass in a lambda expression that contains the behavior. In that lamdba you can name the parameter anything you want, but I would suggest you name it the same name that the method you are mocking names it. This makes it much more understandable what you are actually doing.

Sayed Ibrahim Hashimi

mocks | moq | unit testing Friday, March 26, 2010 5:10:46 AM (GMT Standard Time, UTC+00:00)  #     |