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:

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

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