Freitag, 8. Mai 2015

NEdifis: How we test if something got traced

Sometimes we have the requirement that something needs to be logged. Lets take some examples.
  • a csv importer gets an invalid file. Although the app can handle it, a warning should be logged.
  • an exception got caught and is not re-thrown, an error should be logged.
We use a "log4net trace listener" to get our traces logged (which is another story) so tracing and logging is technically the same for us. 

NEdifis provides an easy to use trace listener to receive all traces or logged messages. It uses the dispose pattern to register and deregister itself, therefore you need to dispose the TestTraceListener.

using (var ttl = new TestTraceListener())
{
    Trace.TraceError("here is a message");

    ttl.MessagesFor(TraceLevel.Error).Should().Contain("here is a message");
}
Fortunately, debug uses the same listener collection than tracing (but Debug has a System.Console like interface). So for debug, you can use the same trace listener and code.

using (var ttl = new TestTraceListener())
{
    Debug.WriteLine("nice debug");

    ttl.MessagesFor(TraceLevel.Verbose).Should().Contain("nice debug");
}

Keep in mind that "System.Debug" only works if you app was compiled with "Debug". For "Release" this list is empty (see unit test).

Keine Kommentare:

Kommentar veröffentlichen