I am trying to unit test a method that throws an exception, and before throwing it has to perform a few tasks, like logging. I am using NSubstitute
and can't get my head around this one.
so my test looks like this
[TestMethod]
[ExpectedException(typeof(IOException))]
public void RecordAnalyser_FileReadFailedInFirstAttempt_WarningLogged()
{
//Arrange
var fileMock = Substitute.For<IFile>();
fileMock.ReadLines(Arg.Any<string>()).Throws(new IOException());
//Act
var recordAnalyser = new RecordAnalyser(fileMock, logger); //--> throws exception.
//Assert
logger.Received(1).Warn(Arg.Any<string>(), Arg.Any<Exception>());
}
Now i want to assert if logger received a warning log, but since the line above sends an exception, and i have an expected exception attribute, test doesn't come to check for assertion.
One dirty code i can think of is to wrap the error statement in a try catch within the test, but its not the neatest.
//Act
try
{
var recordAnalyser = new RecordAnalyser(fileMock, logger);
}
catch (Exception)
{
// eat
}
Code under test -
public RecordAnalyser(IFile file, ILoggerService logger)
{
this.logger = logger;
try
{
names = file.ReadLines(Constants.Names).ToList();
}
catch (System.IO.IOException e)
{
logger.Error("Names file could not be read.", ex);
// How do I test above line without a try catch block in unit test
throw;
}
}
looking for suggestions here.