Подтвердить что ты не робот

Использование Moq для подделки репозитория, который возвращает IQueryable <MyObject>

Как настроить мой 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();
    }

Я в основном застрял в настройке.

4b9b3361

Ответ 1

Не могли бы вы использовать AsQueryable()?

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

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

Ответ 2

Что вы можете сделать, это написать частный вспомогательный метод, который будет генерировать объекты 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();
}

Ответ 3

Я предлагаю не использовать AsQueryable(). он работает только с некоторыми простыми сценариями, прежде чем вы встретите некоторые конкретные методы на вашем языке запросов ORM (Fetch, FetchMany, ThenFetchMany, Include, ToFuture и т.д.).

Лучше использовать в базе данных памяти. Ссылка ниже описывает NHibernate Unit Testing.

Мы можем использовать стандартную СУБД или использовать базу данных в памяти, такую ​​как SQLite, чтобы получить очень быстрые тесты.

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