使用 Moq 模拟 TraceListener
为什么 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我知道这个问题已经存在很长时间了,但是答案如下...
当您通过 TraceSource 编写跟踪事件时,它会调用跟踪侦听器 TraceEvent 方法来执行跟踪 - 因此您需要验证对listener.TraceEvent 的调用,而不是listener.WriteLine...
希望这对某人有帮助!
干杯,
摩根
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...
Hope this helps someone!
Cheers,
Morgan
测试表明必须调用
WriteLine
方法,但事实并非如此。查看代码,这很可能是因为此测试暴露了TraceSource.TraceEvent
或TraceSource.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 yourTraceSource.TraceEvent
orTraceSource.Flush
method. Double-check those methods and you should be good to go!Also, see this question.