[英]Unit test void method with NSubstitute
I want to test if the Update or Insert function is called with a unit test. 我想测试是否用单元测试调用了Update或Insert函数。 What would the unit test look like for this? 为此,单元测试会是什么样?
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;
}
The method is wrapped in an interface which I can mock. 该方法包装在我可以模拟的接口中。
Are you trying to test for a specific call, or are you happy with just testing either call was received? 您是要测试一个特定的电话,还是只测试收到一个电话而感到满意?
For the latter, you can use the ReceivedCalls()
extension method to get a list of all the calls a substitute has received: 对于后者,您可以使用ReceivedCalls()
扩展方法来获取替代者已收到的所有呼叫的列表:
var allCalls = _countryBLL.ReceivedCalls();
// Assert “allCalls” contains “UpdateCountry” and “InsertCountry”
NSubstitute wasn't really designed to support this, so it is quite messy. NSubstitute并不是真正为支持此功能而设计的,因此非常混乱。
To test a specific call was made, we can use Received()
: 要测试特定的通话,我们可以使用Received()
:
_countryBLL.Received().UpdateCountry(Arg.Any<Country>());
// or require a specific country:
_countryBLL.Received().UpdateCountry(Arg.Is<Country>(x => x.CountryCode == expectedCountry));
This requires that the required dependencies have been substituted in for the test, which often results in tests like this: 这要求已将所需的依赖项替换为测试,这通常会导致如下测试:
[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.