Search code examples
c#unit-testinglambdarhino-mocks

Rhino Mocks Testing Lambda Expression


I want to make sure the expression in lambda is same as expected expression

Also I want to write test case for expected value

If I write match it is not working

For example

public bool IsUserActive(User user)
{
    userRepository.Any(x=>x.UserId== user.UserId && x.IsActive);
}

Unit test Case

userRepository.Stub(x=>x.IsActive(Arg<User>.Matches(y=>y.IsActive)).Return(true);

The above expression is not working

I have seen the example but I want to test some lambda expression that return bool by checking condition

not the user name string

stubUserRepository.Stub(x =>
  x.GetUserByName(Arg<string>.Matches(y =>
    y.StartsWith("aye", StringComparison.InvariantCulture) 
      || y.StartsWith("stein", StringComparison.InvariantCulture)))
  .Return(theUser);
Assert.AreSame(theUser, stubUserRepository.GetUserByName("steinegger"));
Assert.AreSame(theUser, stubUserRepository.GetUserByName("ayende"));

Solution

  • Use AbstractConstraint attribute

    public class UserConstraint :AbstractConstraint
    

    and override Equal to match contstraint

      _dataSericeValidator.AssertWasCalled(
                    x =>
                        x.ValidateRequestUser(Arg<UserDto>.Matches(new UserConstraint (_userDto))));