Mocking EventLog and EventLogEntry

I am trying to write unit tests for an application that reports occurrences in EventLog. Right now, when I run the unit tests, I need to create a temporary EventLog, write entries to it and delete the log when done. I do this because I need to return an EventLogEntry object that does not have a constructor.

My question is, are there any ways to mock EventLog in order to be able to return EventLogEntries. The need to write entries to the actual EventLog seems more like integration testing than unit testing for me.

+4
source share
3 answers

It would be correct that this is more an integration test. However, you need to ask yourself what you are actually trying to check here. If this is really a unit test, and you want to test the logic on your EventLogEntries, then you should handle the event log like any other external dependency.

TDD led me to isolate and mock many things that seem strange to taunt, but ultimately saved me from the service nightmares later. i.e. File IO, Logging, Tracing, etc.

I would bind all your CRUD operations to an event log outside the interface and treat it as if it were data access. If you cannot easily create EventLogEntries outside the group, you might even consider creating your own objects that represent the event log entries and use them.

+1
source

This is similar to another question that I just answered today - How can I perform a single test to save a file to disk?

The only difference is that your dependencies are EventLog and related classes. Suppose you just need to write down the text with seriousness.

struct Event { public string Description {get; set;} public Severity Severity {get; set;} } interface Logger { void WriteEvent(Event e); void IEnumerable<Event> GetEvents(); } 

Now, since EventLog is a .Net class that you cannot force the Logger interface, you will need an adapter

 public EventLogAdapter : Logger { //delegates to .Net framework EventLog // Also EventLogEntry is internal to this class - entries will be mapped to Event structs } 

Now all we need is tests ... lightweight like UIA or 123

  • Unit tests for Logger-specific classes will use the layout.
  • Write down integration tests to make sure that the API for EventLogAdapter actually writes material and reads from Windows EventLog
  • Write at least one acceptance test that checks for an end-to-end script that triggers some logging, i.e. checks if the EventLogAdapter adapter is connected correctly.
+3
source

The interfaces are really useful here. Let your class rely on IEventLog instead of EventLog. Then, in your tests, you can make fun of IEventLog and make sure that the methods you expect to call in IEventLog are actually called.

If you want to insert a recorder into your class to capture everything ( class EventLogRecorder : IEventLog ), you can do it too ... and do whatever you need.

Free communication is where you want to go here ...

+1
source

All Articles