我想测试是否通过单元测试调用更新或插入函数。单元测试会是什么样子?
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/