Roar
Roar

Reputation: 2167

Mock Dependency Injection repository with filter

trying to mock repository :

 var expMock = new Mock<IEntityRepository>();
 expMock.Setup(s => s.GetMany(It.IsAny<Expression<Func<Entity, bool>>>()))
        .Returns<IQueryable<Entity>>(r => 
                               new List<Entity>{ new Entity() } }.AsQueryable());

but when i call it:

IEnumerable<Entity> source = _entityRepository.GetMany(w => w.IsActive);

i get an exception:

System.ArgumentException : Object of type 'System.Linq.Expressions.Expression1[System.Func2[Entity,System.Boolean]]' cannot be converted to type 'System.Linq.IQueryable`1[Entity]'.

Upvotes: 2

Views: 1085

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

Simply return value which you want your mocked method to return. In your case it will be IQueryable:

expMock.Setup(s => s.GetMany(It.IsAny<Expression<Func<Entity, bool>>>()))
       .Returns(new List<Entity>{ new Entity() }.AsQueryable());

Generic parameter of Returns method is a type of the argument of invoked method. Returns<IQueryable<Entity>> means that GetMany method should be invoked with parameter of type IQueryable<Entity> which is not true of course. That's why you get this exception.

Method argument is the expression, so correct mock setup should look like:

.Returns<Expression<Func<Entity, bool>>>(e => 
      new List<Entity> { new Entity() }.AsQueryable());

But thus you don't need method argument for providing returned result, use code above.

Upvotes: 3

Patrick Stephansen
Patrick Stephansen

Reputation: 798

Your Returns() statement is binding your Func to be returned when GetMany() is called, not evaluating the expression and returning the result. It should work if you take out the r=>. You can probably get away without the type parameter as well.

Upvotes: 1

Related Questions