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

时间:2010-12-19 03:32:54

标签: unit-testing nunit moq

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

IRepository:

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();
    }

我基本上坚持设置。

3 个答案:

答案 0 :(得分:64)

你不能使用AsQueryable()吗?

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

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

答案 1 :(得分:0)

你可以做的是编写一个私有帮助器方法,它将生成IQueryable个Country对象并让你的模拟返回。

[Test]
public void Can_Get_Correct_Country()
{
    // some private method
    IQueryable<Country> countries = GetCountries(); 

    //Setup
    geographicsRepository.Setup(x => x.GetCountries()).Returns(countries);

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

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

答案 2 :(得分:0)

我建议不要使用AsQueryable()。在您的ORM查询语言(Fetch,FetchMany,ThenFetchMany,Include,ToFuture等)上遇到某些特定方法之前,它仅适用于一些简单的场景。

最好在内存数据库中使用。下面的链接描述了NHibernate单元测试。

  

我们既可以使用标准的RDBMS,也可以使用内存数据库(如SQLite)来获得非常快速的测试。

http://ayende.com/blog/3983/nhibernate-unit-testing