Mam zagwozdkę, czy to wciąż jest test jednostkowy? A mianowicie testuję utworzenie pliku, tak więc wkraczam tu na niebezpieczny teren IO. Teoretycznie nie ma tu nic co by mogło z zewnątrz wpłynąć na wynik testu. W czasie testu sprawdzam czy metoda zapisuje plik z odpowiednią nazwą i czy przy okazji jest wołana inna metoda. Test wygląda następująco:
[Fact]
public void SavePerson_Called_SavesFileWithCorrectNameAndGestCallerName()
{
_fileSerice.CallerName = "";
string folder = Path.Combine("App_Data", "xml");
_fileSerice.SaveFolder = folder;
string filePath = Path.Combine(folder, _personModel.ContentModel.dateRequested);
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
if (File.Exists(filePath))
File.Delete(filePath);
_fileSerice.SavePerson(_xmlPerson, _personModel);
Assert.True(File.Exists(filePath));
Assert.True(filePath.Length > 0);
Assert.Equal("SomeMethod", _fileSerice.CallerName);
_messageServiceMock.Verify(m => m.GetCallerName(It.IsAny<string>()), Times.Once);
}
Testowana metoda:
public void SavePerson(string xmlPerson, PersonModel parsedPerson)
{
LoadDictionaries();
CallerName = _messageService.GetCallerName();
try
{
XmlDocument xmlFile = new XmlDocument();
xmlFile.LoadXml(xmlPerson);
string savePath = Path.Combine(SaveFolder, parsedPerson.ContentModel.dateRequested);
using (TextWriter writer = new StreamWriter(savePath, false, Encoding.UTF8))
{
xmlFile.Save(writer);
}
}
catch (Exception e)
{
_logger.Error(e, MessagesError[CallerName]);
}
}