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