Why did a Moq-mocked method return null

moqnull

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("johndoe@gmail.com");

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();

Best Answer

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.

Related Topic