簡體   English   中英

使用NSubstitute的單元測試無效方法

[英]Unit test void method with NSubstitute

我想測試是否用單元測試調用了Update或Insert函數。 為此,單元測試會是什么樣?

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

該方法包裝在我可以模擬的接口中。

您是要測試一個特定的電話,還是只測試收到一個電話而感到滿意?

對於后者,您可以使用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(…);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM