【发布时间】:2018-03-13 18:01:28
【问题描述】:
我正在尝试围绕我的异常处理编写单元测试,以便我可以验证我的记录器是否正确记录了异常。我使用 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>)
我不确定为什么会失败,因为即使在错误消息中,调用也是相同的。
提前致谢!
更新:
这是测试的构造函数,这是我注入记录器模拟的地方:
public UserCollectionTest()
{
_mongoContext = Substitute.For<IMongoContext<UserDataModel>>();
_logger = Substitute.For<ILogger>();
// create UserCollection with our mock client
_collection = new UserCollection(_mongoContext, _logger);
}
【问题讨论】:
-
请说明您如何创建和注入 ILogger 替代品。
-
我已经用测试的构造函数更新了帖子,这是我注入子的地方。
标签: c# .net unit-testing .net-core nsubstitute