Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why did a Moq-mocked method return null?

Tags:

null

moq

When I try to use my mocked GetProfileFromUserName method, it returns null. A similar method named GetEmail works.

This is the code for retrieving the profile, which doesn't work:

mockUserRepository.Setup(gp => gp.GetProfileFromUserName(userProfile.UserName))
                  .Returns(new Profile { ProfileID = userProfile.ProfileID });

And this is the code for retrieving the email, which works.

mockUserRepository.Setup(em => em.GetEmail(new MockIdentity("JohnDoe").Name))
                  .Returns("[email protected]");

And this is a snippet of the method the mock calls and returns null on instead of a profile:

public ActionResult ShowProfile()
    {
        var profile = _userRepository.GetProfileFromUserName(User.Identity.Name);

What am i doing wrong?

If i replace the userProfile.UserName in the GetProfileFromUserName to It.IsAny();

like image 878
Martin M. Avatar asked Nov 24 '09 12:11

Martin M.


3 Answers

If it returns null, it means that your Setup didn't match the actual call. Check that the userProfile.UserName contains the correct value at the Setup line.

Also, to detect the unmatched calls create your mockUserRepository with the MockBehavior.Strict option.

Hope this helps.

like image 90
Max Galkin Avatar answered Nov 10 '22 16:11

Max Galkin


In my case the mistake was initializing the object with a wrong signature even the code was compiled:

Wrong (The parameter type is int):

_mockEntityServices.Setup(x => x.GetEntities(It.IsAny<int>()))
                   .Returns(new List<Entity>());

Correct (The parameter type is int?):

_mockEntityServices.Setup(x => x.GetEntities(It.IsAny<int?>()))
                   .Returns(new List<Entity>());

Mocked method's signature:

public IList<Entity> GetEntities(int? parentEntityId)
like image 8
karr Avatar answered Nov 10 '22 14:11

karr


For anybody who is trying to return an object, that does not exist at the time of the test setup ("Arrange"), the solution is to use the delegate (Func<>) overload:

mockUserRepository.Setup(gp => gp.GetProfileFromUserName(userProfile.UserName))
     .Returns(() => new Profile { ProfileID = userProfile.ProfileID });
like image 1
Gerwald Avatar answered Nov 10 '22 14:11

Gerwald