0

I am trying to write a unit test for a class, and one of the dependency's method has a LINQ exresssion as a parameter passed into it. Now, I've mocked the dependency. But I am trying to tell this mock to return an object. Which I've done. But I don't know what matching argument 'arg' to pass as a parameter.

I tried to use the solution suggested here, but I couldn't really follow it 100%. Is this the answer? That there is no way?

Code in class under test:

var user = await _userRepository.GetFirstOrDefaultAsync(predicate: x => 
x.Email.ToLower() == dto.Email.ToLower());

I've mocked _userRepository, by saying _userRepositoryMock = Substitute.For<IUserRepository>();

Now, trying to tell it to return an object when called:

_userRepositoryMock.GetFirstOrDefaultAsync(not sure what goes 
here).Returns(user);

In the meantime, I've just passed null like what this guy did.

_userRepositoryMock.GetFirstOrDefaultAsync(null).Returns(user);
user54287
  • 69
  • 9
  • Off-topic, but `x.Email.ToLower() == dto.Email.ToLower()` is not the best way to perform a case-insensitive string comparison in .NET (in part, due to the "Turkish I problem", but it also causes excessive string allocation). If this Linq expression is being transformed into SQL then just use `==` without `ToLower` and it will use your database's default collation which is usually case-insensitive. – Dai Sep 05 '19 at 10:41
  • BTW, I hope you're not using the Generic Repository Anti-Pattern. If you're using Entity Framework (which I assume you are as you're using Linq) then you do not need repository types (and introducing your own repository types only causes headaches. Don't reinvent the wheel and stick to using `DbContext` directly). – Dai Sep 05 '19 at 10:44
  • many thanks for that Dai. Will remove the `ToLower` in the code. – user54287 Sep 05 '19 at 10:45

1 Answers1

1

I think you can use argument matchers:

Arg.Any<Expression<Func<User, bool>>>()
Igor Soengas
  • 61
  • 1
  • 3
  • I did that, and it didn't work when I tried it *duh*. That seems to work now. Many thanks. I had to a add System.Linq.Expressions in the code. – user54287 Sep 05 '19 at 10:50