c# - 使用 NSubstitute 的单元测试无效方法

标签 c# unit-testing 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;
}

该方法包装在一个我可以模拟的接口(interface)中。

最佳答案

您是否正在尝试测试特定调用,或者您是否对仅测试收到的调用感到满意?

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

关于c# - 使用 NSubstitute 的单元测试无效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31316802/

相关文章:

c# - 将 C++ 对象传递给 C#

c# - 在 ASP.NET Core 应用程序中使用 NLog

c# - 如何使用 OnPropertyChanged() 对 setter 进行单元测试;在里面?

c# - NUnit 断言方法错误也在 NUnit.Framework 和 Microsoft.VisualStudio.TestTools.UnitTesting 命名空间中找到

c# - 如果 T 在泛型中为空怎么办?如何省略尖括号

c# - 如何在 C# 中使用 XML 模式正则表达式?

python - Doctest:如何不将设置行算作测试?

unit-testing - 使用 ActiveSupport::TestCase 进行事件管理 Controller 测试

c# - 分配给 void 委托(delegate)的 lambda 是否丢弃 C# 中的非 void 返回类型?

C - 在没有参数的情况下调用用参数声明的函数?