gpt4 book ai didi

unit-testing - 使用 Moq 模拟返回 IQueryable 的存储库

转载 作者:行者123 更新时间:2023-12-03 07:56:21 25 4
gpt4 key购买 nike

如何设置我的 Moq 以返回一些值并让经过测试的服务选择正确的值?

存储库:

public interface IGeographicRepository
{
IQueryable<Country> GetCountries();
}

服务:
public Country GetCountry(int countryId)
{
return geographicsRepository.GetCountries()
.Where(c => c.CountryId == countryId).SingleOrDefault();
}

测试:
    [Test]
public void Can_Get_Correct_Country()
{
//Setup
geographicsRepository.Setup(x => x.GetCountries()).Returns()
//No idea what to do here.

//Call
var country = geoService.GetCountry(1);
//Should return object Country with property CountryName="Jamaica"

//Assert
Assert.IsInstanceOf<Country>(country);
Assert.AreEqual("Jamaica", country.CountryName);
Assert.AreEqual(1, country.CountryId);
geographicsRepository.VerifyAll();
}

我基本上被困在设置上。

最佳答案

你不能用 AsQueryable() ?

List<Country> countries = new List<Country>();
// Add Countries...
IQueryable<Country> queryableCountries = countries.AsQueryable();

geographicsRepository.Setup(x => x.GetCountries()).Returns(queryableCountries);

关于unit-testing - 使用 Moq 模拟返回 IQueryable<MyObject> 的存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4481465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com