PuLSe
PuLSe

Reputation: 21

Unit testing Enterprise Library "Logger" Facade

I'm writing an adapter for Enterprise Library Logging and as per our coding standards, need a way to unit test.

The interface and implementation is simple, but I need a way to check to see that Logger.Write has been called with certain parameters on the log entry. Unfortunately the Logger.Writer does not have a setter, and I don't have any tools to mock a static class.

I'd like to be able to, for example, assert the event ID or the severity for the underlying writer when an adapter method is called.

Upvotes: 1

Views: 778

Answers (1)

Espen Medbø
Espen Medbø

Reputation: 2315

You can implement a custom tracelistener, and use it as your unit test trace listener:

[ConfigurationElementType(typeof(CustomTraceListenerData))]
public class StubTraceListener : CustomTraceListener
{
    private readonly static List<LogEntry> logEntries_ =
        new List<LogEntry>();
    private readonly static List<string> logMessages_ =
        new List<string>();


    public override void Write(string message)
    {
        StubTraceListener.logMessages_.Add(message);
    }

    public override void WriteLine(string message)
    {
        StubTraceListener.logMessages_.Add(message);
    }


    public override void TraceData(TraceEventCache eventCache,
        string source, TraceEventType eventType, int id,
        object data)
    {
        LogEntry le = data as LogEntry;
        if (le != null)
        {
            StubTraceListener.logEntries_.Add(le);
            if (this.Formatter != null)
            {
                this.Write(this.Formatter.Format(le));
                return;
            }
        }
        base.TraceData(eventCache, source, eventType, id, data);
    }

    internal static IList<string> GetLogMessages()
    {
        return new ReadOnlyCollection<string>
            (StubTraceListener.logMessages_);
    }

    internal static IList<LogEntry> GetLogEntries()
    {
        return new ReadOnlyCollection<LogEntry>
            (StubTraceListener.logEntries_);
    }

    internal static void Reset()
    {
        StubTraceListener.logEntries_.Clear();
        StubTraceListener.logMessages_.Clear();
    }

}

Then, in the test project's App.config file include the trace listener like this:

<listeners>
      <add listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.CustomTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0,Culture=neutral" 
           type="Path.To.Your.Project.Folder.StubTraceListener, Your.Test.Project.Name" name="MockTraceListener" />
</listeners>

Then you can easily create the writer as you normally do:

Logger.SetLogWriter(new LogWriterFactory().Create(), false);

Upvotes: 1

Related Questions