Hi all,
First of all, I love the friendly syntax of NSubstitute! Great library!
I seem to be facing a problem. I need to test the following code:
var user = userRepository.Where(o => o.Email == model.Email).FirstOrDefault();
if (user != null) { // Some code }
else { //Some code }
The repository variable above is an instance of
public interface IUserRepository : IRepositoryMongo<User>
{
// Some methods other than Where
}
public interface IRepositoryMongo<T> : IQueryable<T> where T : class
{
// Some methods other than Where
}
So the Where method is inherited from IQueryable.
When I use NSubstitute to set up a mock Where method:
var temp = new List<User>();
temp.Add(new User
{
Email = "
a...@gmail.com"
});
userRepository = Substitute.For<IUserRepository>();
userRepository.Where(user => true).ReturnsForAnyArgs(temp.AsQueryable());
An ArgumentNullException results
on executing the last line above with message: "Value cannot be null. Parameter name: arguments"
Here is the stack trace:
at System.Linq.Expressions.Expression.RequiresCanRead(Expression expression, String paramName)
at System.Linq.Expressions.Expression.ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arg, ParameterInfo pi)
at System.Linq.Expressions.Expression.ValidateArgumentTypes(MethodBase method, ExpressionType nodeKind, ReadOnlyCollection`1& arguments)
at System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, IEnumerable`1 arguments)
at System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, Expression[] arguments)
at System.Linq.Queryable.Where[TSource](IQueryable`1 source, Expression`1 predicate)
at XXXX.Service.UnitTest.Controllers.UserControllerTest.UpdateMobileUserTest() in e:\...\Controllers\UserControllerTest.cs:line 692
The declaration for Where is
public static System.Linq.IQueryable<TSource> Where<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,bool>> predicate)
where TSource should be User in above case.
What could be the problem here? Can we not create a mock method for "Where" or any method which requires a lambda expression using NSubstitute? Am I using NSubstitute wrong? What can I do to mock the following line of project code so I can test the if and else clauses?
var user = userRepository.Where(o => o.Email == model.Email).FirstOrDefault();
Thanks a lot,
Naushervan