2015-07-09 2 views
0

Я хочу проверить, вызвана ли функция Update или Insert с единичным тестом. Что будет для этого модульным тестом?Единичный тест-метод void с NSubstitute

public void LogicForUpdatingAndInsertingCountriesFromMPtoClientApp() 
{ 
    var allCountriesAlreadyInsertedIntoClientDatabase = _countryBLL.GetAllCountries(); 
    var countiresFromMP = GetAllCountriesWithTranslations(); 
    List<Country> countiresFromMPmapped = new List<Country>(); 
    foreach (var country in countiresFromMP) 
    { 
     Country newCountry = new Country(); 
     newCountry.CountryCode = country.Code; 
     newCountry.Name = country.TranslatedText; 
     countiresFromMPmapped.Add(newCountry); 
    } 
    foreach (var country in countiresFromMPmapped) 
    { 
     //check if the country is already inserted into the Client Database, 
     //if it is update, else insert it 
     Country testedCountry = allCountriesAlreadyInsertedIntoClientDatabase 
           .Where(x => x.CountryCode == country.CountryCode) 
           .FirstOrDefault(); 
     //here fallback function for tested country 
     if (testedCountry != null) 
     { 
      var countryToUpdate = _countryBLL.GetCountryByCode(testedCountry.CountryCode); 
      //return _countryBLL.UpdateCountry(countryToUpdate); 
      _countryBLL.UpdateCountry(countryToUpdate); 
     } 
     else 
     { 
      country.CountryId = Guid.NewGuid(); 
      // return _countryBLL.InsertCountryFromMP(country); 
      _countryBLL.InsertCountryFromMP(country); 
     } 

    } 
    return null; 
} 

Метод завернут в интерфейс, который я могу высмеять.

ответ

2

Вы пытаетесь протестировать конкретный вызов, или вы довольны просто тестированием, либо был получен вызов?

Для последнего, вы можете использовать метод ReceivedCalls() расширения, чтобы получить список всех звонков подменять получил:

var allCalls = _countryBLL.ReceivedCalls(); 
// Assert “allCalls” contains “UpdateCountry” and “InsertCountry” 

NSubstitute не был действительно разработан, чтобы поддержать это, так что это довольно грязно ,

Чтобы проверить конкретный вызов был сделан, мы можем использовать Received():

_countryBLL.Received().UpdateCountry(Arg.Any<Country>()); 
// or require a specific country: 
_countryBLL.Received().UpdateCountry(Arg.Is<Country>(x => x.CountryCode == expectedCountry)); 

Это требует, чтобы необходимые зависимости были заменены в течение теста, который часто приводит к тестам, как это:

[Test] 
public void TestCountryIsUpdatedWhen….() { 
    var countryBLL = Substitute.For<ICountryBLL>(); 
    // setup specific countries to return: 
    countryBLL.GetAllCountries().Returns(someFixedListOfCountries); 
    var subject = new MyClassBeingTested(countryBLL); 

    subject.LogicForUpdatingAndInsertingCountries…(); 

    countryBLL.Received().UpdateCountry(…); 
}