'How should my unit tests handle mocking Windows EventLog?

I'm working on writing unit tests for a component that utilizes reading/writing to the Windows Event Log and am having trouble wrapping my head around how to best mock this if my goal is to remove external dependencies (reading and writing to the actual event log).

The component uses EventLogWatcher to subscribe to events such that the event EventRecordWritten is raised when a specific event is published to the event log and my ReadEventLog() delegate function handles logic relating to the newly published event.

My objective in this unit test has been to ultimately test the functionality of ReadEventLog() but I fail to see how to raise the EventRecordWritten event myself so that ReadEventLog() gets called.

I'm looking for any advice on how to properly write unit tests for the Event Log so that I'm not actually writing to the event log but still somehow using my existing ReadEventLog() delegate function(since that's the logic I need to test).



Solution 1:[1]

Since EventLogWatcher does not implement an interface (except IDisposable), you should declare a wrapper class around it which implements IEventLogWatcher members and event:

   public interface IEventLogWatcher
   {
      bool Enabled { get; set; }
      event EventHandler<EventRecordWrittenEventArgs> EventRecordWritten;
   }

   public class EventLogWatcherWrapper : IEventLogWatcher
   {
      private EventLogWatcher eventLogWatcher { get; set; }

      public bool Enabled
      {
         get => eventLogWatcher.Enabled;
         set => eventLogWatcher.Enabled = value;
      }

      public EventLogWatcherWrapper(string path)
      {
         eventLogWatcher = new EventLogWatcher(path);
      }

      public EventLogWatcherWrapper(EventLogQuery eventQuery, EventBookmark bookmark)
      {
         eventLogWatcher = new EventLogWatcher(eventQuery, bookmark);
      }
      public EventLogWatcherWrapper(EventLogQuery eventQuery, EventBookmark bookmark, bool readExistingEvents)
      {
         eventLogWatcher = new EventLogWatcher(eventQuery, bookmark, readExistingEvents);
      }

      event EventHandler<EventRecordWrittenEventArgs> IEventLogWatcher.EventRecordWritten
      {
         add { eventLogWatcher.EventRecordWritten += value; }
         remove { eventLogWatcher.EventRecordWritten -= value; }
      }
   }

Now, you can define the EventLogWatcher property as IEventLogWatcher in your class and pass a mockEventLogWatcher object when you are unit testing.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Behnam Izadi