I need to unit test a method that returns a type I can’t easily fake or instantiate. The type implements IQueryable<T> which I originally thought I could use to my advantage, but I don’t see how at this point.
For example:
public sealed class MyTrickyClass<T> : IQueryable<T>
{
...
}
public MyTrickyClass<T> GetData()
{
return repository.GetAllData();
}
and my unit test
[Test Method]
public void CanGetData()
{
var data = (new List<Record>() { new Record() }).AsQueryable();
var mockRepository = new Mock<IRepository<Record>>();
mockRepository.Setup(s => s.GetAllData()).Returns(data);
MyService service = new MyService(mockRepository.Object);
var result = service.GetData();
Assert.IsNotNull(result);
}
This won’t compile because the return type of GetAllData() is MyTrickyClass<T>. If I try to cast data to a MyTrickyClass<Record> type, the cast fails.
All this makes sense, but it leaves me wondering what the right solution is. What are some workarounds for this kind of situation? I may be able to change the MyTrickyClass, but ideally I’d like to find a solution that leaves it alone.
You could have
MyTrickyClass<T>implement interfaceITrickyClass<T>, which inherits fromIQueryable<T>. That seems minimally invasive to your class itself, and you’d have a good seam for mocking.