用NSubstitute测试void方法

本文关键字:方法 void 测试 NSubstitute | 更新日期: 2023-09-27 18:01:44

我想测试是否使用单元测试调用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;
}

方法被封装在一个接口中,我可以模拟这个接口。

用NSubstitute测试void方法

您是否正在尝试测试特定的呼叫,或者您是否满意仅测试任一呼叫被接收?

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