Moq:模拟GetbyId存储库方法返回null

时间:2012-08-07 11:20:33

标签: nunit moq repository-pattern

我正在使用Moq,我有一个存储库,我正在尝试创建模拟方法。 GetAll方法返回值,但GetById返回null。

var currencyRepo = new Mock<ICurrencyRepository>();
var currencies =  new List<Currency>{new Currency
                                      {
                                          CurrencyCode = "USD",
                                          CurrencyId = 1,
                                      }, 
                                      new Currency
                                             {
                                                  CurrencyCode = "EUR",
                                                  CurrencyId = 2
                                             }};

currencyRepo.Setup(c => c.GetAll()).Returns(currencies);
currencyRepo.Setup(c => c.GetById(It.IsAny<int>())).Returns((int i) =>  currencies.Single(c => c.CurrencyId == i));

var currency = currencyRepo.Object.GetById(1); //This always returns null
//currency is always null
//but calling the GetAll method works!


var currencyList = currencyRepo.Object.GetAll(); //this works!

任何想法?

1 个答案:

答案 0 :(得分:0)

我解决了它在setup方法中更改为long因为GetById接受long参数。 DUH!