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

3

我正在使用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!

有什么想法吗?


2
我在setup方法中将其更改为long类型解决了这个问题,因为GetById接受一个long参数。傻瓜! - kavish247
2
考虑添加对自己问题的回答,这有助于未来访问者解决类似问题! - Jeroen
1个回答

0

我解决了这个问题,因为 GetById 方法接受 long 参数,所以在设置方法中将其更改为 long。 傻瓜!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接