我有一个方法,它有一行代码:
_logger.LogError(exception, $"Encountered {exception.GetType().Name}. Unable to verify user with id {user.UserId}");
这有一个对应的单元测试,其断言如下:
var logger = Substitute.For<ILogger<SyncService>>();
// other Arrange, Act, Assert steps
logger.Received(1).LogError(exception, "Encountered NullReferenceException. Unable to verify user with id 1");
这项测试运行良好.
但是,由于我们遇到了一些问题,现在需要将此日志(log)转换为 struct 化日志(log).
因此,现在类中的行如下所示:
_logger.LogError(exception, "Encountered {exceptionType}. Unable to verify user with id {userId}", exception.GetType().Name, user.UserId);
但现在,当我将断言更改为以下内容时,测试失败:
logger.Received(1).LogError(exception, "Encountered {exceptionType}. Unable to verify user with id {userId}", "NullReferenceException", 1);
错误消息如下.我删除了不需要的堆栈跟踪,以便只突出显示重要的部分:
NSubstitute.Exceptions.ReceivedCallsException : Expected to receive exactly 1 call matching:
Log<FormattedLogValues>(Error, 0, Encountered NullReferenceException. Unable to verify user with id 1, System.NullReferenceException: Test Exception
at NSubstitute.ExceptionExtensions.ExceptionExtensions.<>c__DisplayClass0_0.<Throws>b__0(CallInfo _)
...// complete stack trace ...
Actually received no matching calls.
Received 1 non-matching call (non-matching arguments indicated with '*' characters):
Log<FormattedLogValues>(Error, 0, *Encountered NullReferenceException. Unable to verify user with id 1*, System.NullReferenceException: Test Exception
at NSubstitute.ExceptionExtensions.ExceptionExtensions.<>c__DisplayClass0_0.<Throws>b__0(CallInfo _)
起初,我无法弄清楚自己做错了什么.从这两条消息看,似乎使用正确的参数调用了正确的方法,但该消息仍被标记为不匹配.
但在深入研究之后,我意识到标记的消息实际上是对FormattedLogValues
的ToString()
调用,该调用在抛出异常时发生.在内部,它试图将string
的实例与FormattedLogValues
的实例进行比较
我try 在Log<FormattedLogValues>
上直接断言,但似乎FormattedLogValues
类不可用于外部使用.
这个问题早先是这样解决的:https://github.com/nsubstitute/NSubstitute/issues/384
但现在, struct FormattedLogValues
不再可供公众使用.这里有一个悬而未决的问题:https://github.com/dotnet/runtime/issues/67577
但现在的问题是,我如何测试这一点?我知道Moq有一个名为It.IsAnyType()
的方法,可以用来忽略消息模板的类型,但NSubicide有类似的方法吗?
我在StackOverflow中看到了其他一些有类似问题的帖子,但当使用 struct 化日志(log)时,答案似乎不起作用