3
votes

I'm learning how to write unit tests and am a little stuck on using Mocks. I'm using Moq for mocking. I am using the built in test framework that comes with VS 2012. I can switch to NUnit if that is better (and would solve my problem). I have a unit of work pattern setup. The method I'm testing is for resetting a user's password. I am telling Moq to return a list of users based on a unique code which is what is called in the method I'm testing:

var mock = new Mock<IUnitOfWork>();
        mock.Setup(u => u.UserRepository.Get(t => t.PassResetCode.Equals("test1"), null, "")).Returns(
            new List<User>
        {
            new User { UserId = 4, FirstName = "Test4", LastName = "LastName", Email = "[email protected]", Salt = salt, Password = pass, AccountConfirmed = true, PassResetCode = "test1", PassResetExpire = new Nullable<DateTime>(DateTime.Now.Add(ts)) },                
        });

In the method I'm testing it calls the following:

var users = unitOfWork.UserRepository.Get(u => u.PassResetCode.Equals(code));

As far as I can tell, it is not returning the list of users I'm creating in the test here. Do I need to mock the repository too that is within the Unit of work class? Or is just mocking the unit of work interface enough? I can post more of the code if that helps.

3

3 Answers

1
votes

Your repository accepts delegate and you're setting an expectation to expect particular delegate t => t.PassResetCode.Equals("test1"). I think mock inside will compare the passed predicate to this delegate. Different delegate instances will not match with 99.99% probability. You should probably avoid setting up specific constraint for predicate in this particular expectation and use It.IsAny<>() instead.

var mock = new Mock<IUnitOfWork>();
mock.Setup(It.IsAny<Func<User, bool>>(), null, ""), ...).Returns(...)
0
votes
var mock = new Mock<IUnitOfWork>();
        mock.Setup(u => u.UserRepository.Get("test1", null, "")).Returns(
            new List<User>
        {
            new User { UserId = 4, FirstName = "Test4", LastName = "LastName", Email = "[email protected]", Salt = salt, Password = pass, AccountConfirmed = true, PassResetCode = "test1", PassResetExpire = new Nullable<DateTime>(DateTime.Now.Add(ts)) },                
        });

You have to be sure you are passing exactly those parameters. Or you can use the syntax It.IsAny<TYPE>() for any parameter you do not care. Or you can do It.Is<TYPE>(condition) to check for the parameter.

0
votes

Assuming you are using Moq, the issue is the setup method doesn't handle lambdas like that. You would need to use It.IsAny<Func<T, bool>> () as your first argument.