我正在尝试对引发异常的方法进行单元测试,并且在引发异常之前,它必须执行一些任务,例如记录日志。我正在使用NSubstitute,无法解决这个问题。
所以我的测试看起来像这样
[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>());
}
现在,我想断言记录器是否收到警告日志,但是由于上面的行发送了异常,并且我具有预期的异常属性,因此测试不会检查断言。
我能想到的一个肮脏的代码是将错误语句包装在测试中的try catch中,但不是最整洁的代码。
//Act
try
{
var recordAnalyser = new RecordAnalyser(fileMock, logger);
}
catch (Exception)
{
// eat
}
被测代码-
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;
}
}
在这里寻找建议。
相关分类