Moq设置不适用于接口方法,并使用IQueryable结果输入moqed方法

时间:2012-09-07 12:43:32

标签: linq mocking installation moq iqueryable

我在模拟一个名为Query的方法时遇到问题,该方法返回一个IQueryable接口,我不知道为什么。

我尝试用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。是的,我知道,我必须使用集成测试,但这是我的任务。

2 个答案:

答案 0 :(得分:2)

您的工厂返回new ObjectContextRepository(It.IsAny<string>())而不是您的模拟(后来甚至定义为您的工厂)。所以你的测试是针对真正的实现而不是模拟的。

顺便说一句,在It.IsAny<string>()内使用Returns没有任何意义,它什么也没做。

答案 1 :(得分:0)

有时停止探索问题并发布问题非常有效。答案很快就来了......

原因在于Mocked对象的Object属性。 我变了

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>();

        ObjectContextRepositoryFactory = new Mock<IObjectContextRepositoryFactory>();
        ObjectContextRepositoryFactory.Setup(x => x.NewInstance(false))
                                      .Returns(**ObjectContextRepository.Object**);

        CurrencyRateManager = new CurrencyRateManager(**ObjectContextRepositoryFactory.Object**);

它有效。