c# – NSubstitute ILogger .NET Core
作者:互联网
我试图围绕我的异常处理编写单元测试,以便我可以验证我的记录器正确记录异常.我使用NSubstitute作为模拟框架和Microsoft.Extensions.Logging.ILogger我必须遵循我的测试:
[Fact]
public void LogsExcpetionWhenErrorOccursInCreate()
{
var newUser = new UserDataModel
{
FirstName = "Rick",
MiddleName = "Jason",
LastName = "Grimes",
Email = "rick.grimes@thedead.com",
Created = new DateTime(2007, 8, 15)
};
var exception = new Exception("Test Exception");
// configure InsertOne to throw a generic excpetion
_mongoContext.InsertOne(newUser).Returns(x => { throw exception; });
try
{
_collection.Create(newUser);
}
catch
{
// validate that the logger logs the exception as an error
_logger.Received().LogError(exception.Message);
}
}
使用以下方法测试日志记录:
public UserDataModel Create(UserDataModel user)
{
try
{
return MongoContext.InsertOne(user);
}
catch(Exception e)
{
_logger?.LogError(e.Message);
throw new DataAccessException("An error occurred while attempting to create a user.", e);
}
}
我的测试失败,出现以下错误:
Message: NSubstitute.Exceptions.ReceivedCallsException : Expected to receive a call matching:
Log<Object>(Error, 0, Test Exception, <null>, Func<Object, Exception, String>)
Actually received no matching calls.
Received 1 non-matching call (non-matching arguments indicated with '*' characters):
Log<Object>(Error, 0, *Test Exception*, <null>, Func<Object, Exception, String>)
我不确定为什么这会失败,因为即使在错误消息中,调用也是一样的.
提前致谢!
更新:
这是测试的构造函数,这是我注入logger mock的地方:
public UserCollectionTest()
{
_mongoContext = Substitute.For<IMongoContext<UserDataModel>>();
_logger = Substitute.For<ILogger>();
// create UserCollection with our mock client
_collection = new UserCollection(_mongoContext, _logger);
}
解决方法:
LogError不是ILogger方法,因此当您尝试检查此方法是否使用某些参数调用时,NSubstitute会尝试以某种方式处理它(我不知道具体如何)并失败.
LogError扩展方法的代码是:
public static void LogError(this ILogger logger, string message, params object[] args)
{
if (logger == null)
throw new ArgumentNullException("logger");
logger.Log<object>(LogLevel.Error, (EventId) 0, (object) new FormattedLogValues(message, args), (Exception) null, LoggerExtensions._messageFormatter);
}
因此,您必须检查是否已调用Log方法.
我简化了你的例子.我认为这个想法应该是明确的.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var logger = Substitute.For<ILogger>();
try
{
Create(logger);
}
catch
{
logger.CheckErrorMessage("My Message");
}
}
public string Create(ILogger logger)
{
try
{
throw new Exception("My Message");
}
catch (Exception e)
{
logger?.LogError(e.Message);
throw new Exception("An error occurred while attempting to create a user.", e);
}
}
}
public static class TestExtensions
{
public static void CheckErrorMessage(this ILogger logger, string message)
{
logger.Received().Log(
LogLevel.Error,
Arg.Any<EventId>(),
Arg.Is<object>(o => o.ToString() == message),
null,
Arg.Any<Func<object, Exception, string>>());
}
}
标签:c,net,unit-testing,net-core,nsubstitute 来源: https://codeday.me/bug/20190611/1216829.html