使用 Moq 模拟 TraceListener

发布于 2024-10-13 17:51:37 字数 357 浏览 8 评论 0原文

为什么 Moq 验证失败并显示“Moq.MockException:未在模拟上执行调用”?

var mock = new Mock<TraceListener>();
var ts = new TraceSource("traceSourceName", SourceLevels.Verbose);
ts.Listeners.Add(mock.Object);

var message = "the message";

ts.TraceEvent(TraceEventType.Verbose, 0, message);
ts.Flush();
mock.Verify(x => x.WriteLine(message));

Why does the Moq Verify fail with a "Moq.MockException : Invocation was not performed on the mock"?

var mock = new Mock<TraceListener>();
var ts = new TraceSource("traceSourceName", SourceLevels.Verbose);
ts.Listeners.Add(mock.Object);

var message = "the message";

ts.TraceEvent(TraceEventType.Verbose, 0, message);
ts.Flush();
mock.Verify(x => x.WriteLine(message));

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

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

发布评论

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

评论(2

旧街凉风 2024-10-20 17:51:38

我知道这个问题已经存在很长时间了,但是答案如下...

当您通过 TraceSource 编写跟踪事件时,它会调用跟踪侦听器 TraceEvent 方法来执行跟踪 - 因此您需要验证对listener.TraceEvent 的调用,而不是listener.WriteLine...

var mock = new Mock<TraceListener>();
var ts = new TraceSource("traceSourceName", SourceLevels.Verbose);
ts.Listeners.Add(mock.Object);

var message = "the message";

ts.TraceEvent(TraceEventType.Verbose, 0, message);

mock.Verify(x => x.TraceEvent(It.IsAny<TraceEventCache>(), "traceSourceName", 
    TraceEventType.Verbose, 0, message), Times.Once(), "Expected a trace");

希望这对某人有帮助!

干杯,

摩根

I know this question has been on here a long time however the answer is as follows...

When you write a trace event through TraceSource it calls your trace listeners TraceEvent method to do the tracing - so you need to verify calls to listener.TraceEvent, not listener.WriteLine...

var mock = new Mock<TraceListener>();
var ts = new TraceSource("traceSourceName", SourceLevels.Verbose);
ts.Listeners.Add(mock.Object);

var message = "the message";

ts.TraceEvent(TraceEventType.Verbose, 0, message);

mock.Verify(x => x.TraceEvent(It.IsAny<TraceEventCache>(), "traceSourceName", 
    TraceEventType.Verbose, 0, message), Times.Once(), "Expected a trace");

Hope this helps someone!

Cheers,

Morgan

晒暮凉 2024-10-20 17:51:38

测试表明必须调用 WriteLine 方法,但事实并非如此。查看代码,这很可能是因为此测试暴露了 TraceSource.TraceEventTraceSource.Flush 方法中的错误。仔细检查这些方法,你应该可以开始了!

另请参阅此问题

The test states that the WriteLine method must be called, but it is not. Looking at the code this is most likely because this test has exposed a bug in your TraceSource.TraceEvent or TraceSource.Flush method. Double-check those methods and you should be good to go!

Also, see this question.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文