Hello,
I have an issue with substituting a method which returns IMongoQueryable.
The method:
public IMongoQueryable<T> GetGetMyTypeQueryable()
{
private readonly IMongoCollection<T> _collection;
return _collection.AsQueryable();
}
Method is shortened for brevity purposes, but general idea is that it returns an IMongoQueryable.
The IMongoQueryable is used to Inject() a generated filter later and order documents before making a call to get the data (ToListAsync()):
var result = _mongoDBService.GetGetMyTypeQueryable();
var filter = GenerateFilterDefinition(requestFilter); //returns FilterDefinition<MyMessageType>
var queryableResult = result
.Where(x => filter.Inject())
.Take(MaxAuditSearchResults);
The code works fine.
The issue I have is trying to cover with unit tests using NSubstitute and XUnit.
Ideally I would like to get back an IMongoQueryable from a IEnumerable.
I tried with the following extension method:
public static IMongoQueryable<T> GenerateIMongoQueryable<T>(List<T> listToMock)
{
var expectedQueryable = listToMock.AsQueryable();
var mockQueryable = Substitute.For<IMongoQueryable<T>>();
mockQueryable.ElementType.Returns(expectedQueryable.ElementType);
mockQueryable.Expression.Returns(expectedQueryable.Expression);
mockQueryable.Provider.Returns(expectedQueryable.Provider);
mockQueryable.GetEnumerator().Returns(expectedQueryable.GetEnumerator());
return mockQueryable;
}
But this gives me the following error when running the unit test (specifically in .Where(x => filter.Inject()) part):
System.InvalidCastException : Unable to cast object of type 'System.Linq.EnumerableQuery`1[MyMessageType]' to type 'MongoDB.Driver.Linq.IMongoQueryable`1[MyMessageType]'.
As I can see the AsQueryable method IMongoQueryable AsQueryable is an extension of IMongoCollection. How can I create an IMongoQueryable from List to be used for testing?
Thanks in advance.