1

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

4

2 回答 2

2

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

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

于 2012-09-07T12:48:31.883 回答
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**);

它有效。

于 2012-09-07T12:59:55.380 回答