Search code examples
c#unit-testingloggingtrace

How to unit test a custom logger which is a wrapper around tracesource object


I have a wrapper around TraceSource class. I'm wondering how can I unit test it. Since I need to configure app.config file in order to add trace listeners to TraceSource object, add SwtichSource etc. So would it be valid to manually add app.config file in unit test dll and configure it to do unit testing? I know we can progrmatically do all this but the way I have created a wrapper around TraceSource it looks quite ticklish or may be impossible. Any suggestions will be more than welcome.

public class Logger : ILogger
{

    private const int ERROR_EVENT_ID = 2;
    private const int DEBUG_EVENT_ID = 5;
    private  static TraceSource source;

    public Logger(string nameOfComponent)
    {
         source = new TraceSource(nameOfComponent);
    }

    public  void LogDebug(string message, string methodName)
    {
        if (string.IsNullOrEmpty(message) || string.IsNullOrEmpty(methodName))
            throw new ArgumentNullException("message, methodName can't be null or empty");

        source.TraceEvent(TraceEventType.Verbose, DEBUG_EVENT_ID);
    }

    public  void LogError(string methodName, Exception ex)
    {
        LogError(null, methodName, ex);
    }

    public  void LogError(string message, string methodName, Exception ex)           {
        if (String.IsNullOrEmpty(message) || String.IsNullOrEmpty(methodName) || ex == null)
            throw new ArgumentNullException("message, methodName and exception can't be null or empty");

        source.TraceData(TraceEventType.Error, ERROR_EVENT_ID, message, methodName, ex);
    }
  }

Solution

  • Rather than having this class create a TraceSource for itself, inject the TraceSource into it via constructor injection. That way, in your unit tests, you can initialize the TraceSource with listeners that let you record what has been done to it.

    You should also make sure your source field is not static, since it's getting initialized by the non-static constructor and is used by non-static methods.