How to mock chained Linq methods in Moq

Viewed 2255

I have a query that goes

var myRecord = myRepository.All().Any(e => e.Id == id);

I mocked it with this

this._myMockRepository
    .Setup(s => s.All().Any(It.IsAny<Expression<Func<MyObject, bool>>>()))
    .Returns(this.GetFakeMyObjects().Any(t => t.Id == 1));

How do I mock the .All().Any(...) call? The exception I get is a NotSupportedException with message :

Expression references a method that does not belong to the mocked object: s => s.All().Any < MyRepositoryObject > (It.IsAny < Expression`1 > ())

I tried breaking it up like so

this._myMockRepository
    .Setup(s => s.All(It.IsAny<Expression<Func<MyObject, bool>>>()))
    .Returns(this.GetFakeMyObjects());
this._myMockRepository
    .Setup(s => s.All().Any(It.IsAny<Expression<Func<MyObject, bool>>>()))
    .Returns(this.GetFakeMyObjects().Any(t => t.Id == 1));

Fairly new to Moq so any tips would be appreciated.

2 Answers
Related