使用Moq模拟返回IQueryable <MyObject>的存储库

Sha*_*ean 35 nunit unit-testing moq

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

IRepository:

public interface IGeographicRepository
{
    IQueryable<Country> GetCountries();
}
Run Code Online (Sandbox Code Playgroud)

服务:

public Country GetCountry(int countryId)
{
    return geographicsRepository.GetCountries()
             .Where(c => c.CountryId == countryId).SingleOrDefault();
}
Run Code Online (Sandbox Code Playgroud)

测试:

    [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();
    }
Run Code Online (Sandbox Code Playgroud)

我基本上坚持设置.

And*_*ker 66

你不能使用AsQueryable()吗?

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

geographicsRepository.Setup(x => x.GetCountries()).Returns(queryableCountries);
Run Code Online (Sandbox Code Playgroud)