gpt4 book ai didi

c# - NSubstitute ILogger .NET Core

转载 作者:太空狗 更新时间:2023-10-29 22:21:21 26 4
gpt4 key购买 nike

我正在尝试围绕我的异常处理编写单元测试,以便我可以验证我的记录器是否正确记录了异常。我使用 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>)

我不确定为什么会失败,因为即使在当时的错误消息中,调用也是相同的。

提前致谢!

更新:

这是测试的构造函数,这是我注入(inject)记录器模拟的地方:

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 会尝试以某种方式处理它(我不知 Prop 体是如何处理的)但失败了。

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# - NSubstitute ILogger .NET Core,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46529349/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com