c# nUnit,日志模拟验证在代码中多次调用的地方不起作用

发布于 2025-01-15 20:46:02 字数 699 浏览 1 评论 0 原文

我正在从事 .NET CORE 3.1 nUnit 测试并尝试验证日志。我注意到,单次调用的日志确实可以识别并工作,并且如果相同的登录循环(例如记录不存在时的 log.logDebug)不适用于验证代码。

log 是 ILogger 模拟

log.LogDebug("No files discovered in testing....");

Test的实例

_loggerMoq.Verify(
            x => x.Log(
                LogLevel.Debug,
                It.IsAny<EventId>(),
                It.Is<It.IsAnyType>((o, t) => string.Equals("No files discovered in testing....", o.ToString(), StringComparison.InvariantCultureIgnoreCase)),
                It.IsAny<Exception>(),
                It.IsAny<Func<It.IsAnyType, Exception, string>>()),
            Times.Once);

I am working on .NET CORE 3.1 nUnit tests and trying to verify log. I have notice that log that call single time does recognize and work and if same log in loop for example log.logDebug when record does not exist does not work with verify code.

log is instance of ILogger mock

class

log.LogDebug("No files discovered in testing....");

Test

_loggerMoq.Verify(
            x => x.Log(
                LogLevel.Debug,
                It.IsAny<EventId>(),
                It.Is<It.IsAnyType>((o, t) => string.Equals("No files discovered in testing....", o.ToString(), StringComparison.InvariantCultureIgnoreCase)),
                It.IsAny<Exception>(),
                It.IsAny<Func<It.IsAnyType, Exception, string>>()),
            Times.Once);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

嘿看小鸭子会跑 2025-01-22 20:46:02

您必须将 It.IsAny>()), 更改为 (Func)It.IsAny< ;object>()),

不确定为什么会这样,这是 Moq 库中的一个已知错误。

You have to change It.IsAny<Func<It.IsAnyType, Exception, string>>()), to (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()),

Not sure why this works, it is a known bug in the Moq library.

晨曦÷微暖 2025-01-22 20:46:02
_loggerMoq.Verify(
            x => x.Log(
                LogLevel.Debug,
                It.IsAny<EventId>(),
                It.Is<It.IsAnyType>((o, t) => string.Equals("No files discovered in testing....", o.ToString(), StringComparison.InvariantCultureIgnoreCase)),
                It.IsAny<Exception>(),
                (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()),
            Times.AtLeastOnce());
_loggerMoq.Verify(
            x => x.Log(
                LogLevel.Debug,
                It.IsAny<EventId>(),
                It.Is<It.IsAnyType>((o, t) => string.Equals("No files discovered in testing....", o.ToString(), StringComparison.InvariantCultureIgnoreCase)),
                It.IsAny<Exception>(),
                (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()),
            Times.AtLeastOnce());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文