After some google research and experimentation I found that it was not worth to mock methods that return IQueryable or IQueryable because in order to use it programmers have to make use of extension methods. And this kind of methods are not supported by Moq ( a minimalistic mock framework ). This is the DAO interface I want to test.
public interface IDAOFactory
{
public abstract IQueryable Query();
}
This is the moq unit test that fails, since I can´t use Linq directly.
[Test]
public void LinqQueryTest()
{
// This moq configuration will trigger an exception
// Can´t make use of extension methods
.Setup(d => (from o in d.Query()
daoFactoryMock.Id >= 0
where o.Id).ToList())
select o.Returns( new List() { 1, 2 } );
}
It turns out that the solution is easily solved by using a collection as a data source.
[Test]
public void LinqQueryTest()
{
// Creates a IQueryable from a Collection
= new List() {
IList lstOrders .Object,
orderMock1.Object,
orderMock2.Object };
orderMock3= lstOrders.AsQueryable();
IQueryable orderQuery
// Configures the Query to return IQueryable implementation
.Setup(d => d.Query()).Returns(orderQuery);
daoFactoryMock
// Now the linq queries can be used naturally
= (from o in daoFactoryMock.Object.Query()
IList lstResult .Id >= 0 Select o).ToList();
where o
// Checking output results
.AreEqual(3, lstResult.Count);
Assert}
It is important to notice that the collection elements that should also be mock objects must contain all the necessary data in order to make the correct test.