Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking a TraceListener with Moq

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));
like image 453
Lybecker Avatar asked Jan 22 '11 18:01

Lybecker


1 Answers

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

like image 52
Morgan Skinner Avatar answered Nov 06 '22 08:11

Morgan Skinner