我在模拟返回 IQueryable 接口的名为 Query 的方法时遇到问题,我不知道为什么。
我尝试使用 Moq 框架模拟的方法:
public class ObjectContextRepository : IObjectContextRepository
{
.....
private ObjectContext _objectContext = null;
public IQueryable<TEntity> Query<TEntity>() where TEntity : class
{
// Moq Setup doesn't work and debugger enters this code:
return ObjectContext.CreateObjectSet<TEntity>();
}
...
}
测试示例:
ObjectContextRepositoryFactory = new Mock<IObjectContextRepositoryFactory>();
ObjectContextRepositoryFactory.Setup(x => x.NewInstance(false))
.Returns(new ObjectContextRepository(It.IsAny<string>()));
CurrencyRateManager = new CurrencyRateManager(new ObjectContextRepositoryFactory("connection"));
ObjectContextRepository = new Mock<IObjectContextRepository>();
CurrencyExchangeRate rate1 = new CurrencyExchangeRate {EXCHANGE_DATE = new DateTime(2012, 09, 07)};
CurrencyExchangeRate rate2 = new CurrencyExchangeRate {EXCHANGE_DATE = new DateTime(2012, 09, 06)};
IList<CurrencyExchangeRate> list = new List<CurrencyExchangeRate> { rate1, rate2 };
// I wait that Query() method will return me a list with rates.
ObjectContextRepository.Setup(x => x.Query<CurrencyExchangeRate>()).Returns(list.AsQueryable());
using (IObjectContextRepository context = ObjectContextRepositoryFactory.Object.NewInstance())
{
// Mock doesn't work and debugger enters custom method context.Query<>() and throws an exception
var maxDateQuery = context.Query<CurrencyExchangeRate>()
.Where(c => c.EXCHANGE_DATE < new DateTime(2012, 09, 07));
}
PS。是的,我知道,我必须使用集成测试,但这是我的任务。