首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Moq模拟返回IQueryable<MyObject>的存储库

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

Stack Overflow用户
提问于 2010-12-19 11:32:54
回答 3查看 14.4K关注 0票数 43

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

IRepository:

代码语言:javascript
复制
public interface IGeographicRepository
{
    IQueryable<Country> GetCountries();
}

服务:

代码语言:javascript
复制
public Country GetCountry(int countryId)
{
    return geographicsRepository.GetCountries()
             .Where(c => c.CountryId == countryId).SingleOrDefault();
}

测试:

代码语言:javascript
复制
    [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();
    }

我基本上被困在设置中了。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-12-19 11:40:04

你不能使用AsQueryable()吗?

代码语言:javascript
复制
List<Country> countries = new List<Country>();
// Add Countries...
IQueryable<Country> queryableCountries = countries.AsQueryable();

geographicsRepository.Setup(x => x.GetCountries()).Returns(queryableCountries);
票数 81
EN

Stack Overflow用户

发布于 2010-12-19 11:40:37

您可以做的是编写一个私有助手方法,该方法将生成一个Country对象的IQueryable,并让您的模拟返回该you。

代码语言:javascript
复制
[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();
}
票数 0
EN

Stack Overflow用户

发布于 2013-01-06 02:28:39

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

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

我们可以使用标准的关系型数据库管理系统,也可以使用内存中的数据库,例如SQLite,以获得非常快的测试速度。

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4481465

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档