5

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));
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Lybecker
  • 618
  • 5
  • 16

2 Answers2

6

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

Morgan Skinner
  • 490
  • 5
  • 11
  • +1 - Nice answer! Unrelated to your answer, [your quantization code](http://sariendotnet.googlecode.com/svn-history/r20/trunk/convert/AgiConvert/AgiConvert/src/Quantizer.cs) is quite popular and included in a lot of other libraries under many licenses. Is there a place I can find your original Quantizer & OctreeQuantizer classes so I can add the appropriate references & recognition. Thanks! – Brandon Boone Apr 12 '13 at 01:54
  • Brandon - thanks! The original article is on MSDN, http://msdn.microsoft.com/en-us/library/aa479306.aspx. This includes a link to the source code. Feel free to link back to this article, I no longer work for Microsoft but a link back to the original is better than nothing! – Morgan Skinner Apr 17 '13 at 15:23
  • Great! Thanks so much for the reference and the code. It's certainly saved me a tun of time. – Brandon Boone Apr 17 '13 at 20:04
0

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.

Community
  • 1
  • 1
vidstige
  • 12,492
  • 9
  • 66
  • 110