JustMock: Returning null in unit tests

Sometimes it is necessary to return null inside a unit test. JustMock has its own style doing this. Take a look at the following method:


public string GetUsername(Guid userId)
{
  User user = UserRepository.GetUser(userId);
  string username = string.Empty;
  if (user != null)
    username = user.Username;
  return username;
}

If you want to test that the method returns an empty string if no user is found inside your repository, you have to arrange that your mocked repository returns null.

The testmethod should look like this:


[TestMethod]
public void GetUsername_Returns_Empty_String_If_User_Not_Found()
{
  IUserRepository userRepository = Mock.Create<IUserRepository>();
  Guid userId = Guid.NewGuid();
  Mock.Arrange(() => userRepository.GetUser(userId)).Returns(null);

  UserManager userManager = new UserManager(userRepository);
  string username = userManager.GetUsername(userId);
	 
  Assert.IsTrue(username.Equals(string.Empty));
}

The code won’t compile, because the line


Mock.Arrange(() => userRepository.GetUser(userId)).Returns(null);

throws an error.

The correct way would be


Mock.Arrange(() => userRepository.GetUser(userId)).Returns((User)null);

– or –


Mock.Arrange(() => userRepository.GetUser(userId)).Returns(() => null);


Kick It auf dotnet-kicks.de

One thought on “JustMock: Returning null in unit tests

  1. thanks, was trying to force a null return and couldn’t figure out how, your post was helpful and got me back to work!

Leave a Reply

Your email address will not be published.


*