I want to test if the Update or Insert function is called with a unit test. 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:
var allCalls = _countryBLL.ReceivedCalls();
// Assert “allCalls” contains “UpdateCountry” and “InsertCountry”
NSubstitute wasn’t really designed to support this, so it is quite messy.
To test a specific call was made, we can use 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(…);
}