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();
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.
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)
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With