繁体   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