Logging test results with NUnit
Recently, a question popped at StackOverflow asking what needed to be done in order to custom-log unit test failures. Not many people know that, but NUnit offers extensions API which could be utilized to solve this very problem. In this post, we’ll see how.
NUnit Addins API
To extend NUnit we need to implement an addin listening to events NUnit triggers during different stages of tests execution. Our response to such events (preferably test finished event) will be logging some data to a file. As simple as that. Let’s see what do we got:
- IAddin interface & NUnitAddinAttribute – these two will be used to “introduce” our addin to NUnit and make sure it is loaded and present during tests execution
- EventListener – this interface (yes, an interface) will be our primary implementation doing actual logging when some test-related event occurs
All the components we need are available as NUnit.AddinsDependencies package, available on NuGet.
In order for NUnit to detect our addin we need to mark class implementing it with NUnitAddinAttribute and implement IAddin interface:
We’ll also kick off unit tests project with the very first test verifying whether our addin is discoverable. With FluentAssertions, it is as easy as:
Next, the addin must hook itself to NUnit’s extensions system via IAddin.Install method:
This is to make sure we receive notifications when test-related event occurs.
3. EventListener interface
This interface offers notifications for various stages of test suite execution. The one that we want to hook to is TestFinished method. We’ll simply log time, result and test name. If a test fails, we also save an error message:
That’s all you need to log test results to custom file. Simply copy NUnitFileLoggingAddin class files to your test project and your tests will be logged to Log.txt file. However, we are far from done.
In its current form our addin is rather poor piece of software. We lack proper unit tests (File.Open and DateTime.Now sort of get in the way) and even changing log file name would require recompilation. This is no good.
Before we jump straight to refactoring let’s take a moment to think about possible improvements and extension points of our addin.
1. Code quality improvements
- We should have unit tests for logging part. This requires abstracting file access and time.
- NUnit will not allow us to inject abstracted dependencies via constructor arguments (addin instances are created via reflection). We need to find a way around it.
- NUnit will not allow to have addin in separate assembly (it must be in the same one as our tests)1. We want to have majority of features in a base class, so that all is required is creating derived type in our test assembly.
- (optional) Opening a file for writing with each test execution is not very efficient thing to do. We’d be better storing results and writing them all at once.
- It would be good if we could change log file name/location.
- …or log message format.
- (optional) Instead of to a file, maybe we could write test results to a database or a web service.
Refactoring for testability and extensibility
Our first step would be to introduce abstractions over file system and time, IFileStreamFactory and ITimeProvider, respectively. Now, we also need to solve the problem with providing those abstractions. Since NUnit will create addin instance using reflection, there should be working parameterless constructor for our addin. Yet we also need constructor with parameters to pass mocked dependencies in unit test. What do we do? We use an anti-pattern – poor man’s DI:
We’re good to write few tests for the logging part. As you might know from my previous posts, unit testing, IDisposable and Stream don’t play along very well. To test I/O interactions we will be using StreamRecorder class:
Test above simply verifies whether correct message is written to log file. We should add couple more tests for logging functionality before we proceed to extensibility refactoring. All unit tests written for NUnitFileLoggerAddin can be viewed at my GitHub repository.
At this point our addin is fully usable. We might even use it to record its own tests - all we need is a local type inheriting from our base NUnitFileLoggerAddin class:
This is a minor nuance given how we want to have our addin reusable, but luckily majority of the features can remain in base class.
Back to extension points. As I mentioned, we want to have control over the output formatting and log file path. To achieve this, our base NUnitFileLoggerAddin will expose several protected virtual members:
Now, our LoggerAddin can for example change the way failed tests are reported:
Although we only did simple logging, available API offers much more in terms of extensibility. For example, similar mechanism can be used to write database integration testing API where NUnit will gather all tests marked with special database attribute, and before any of them is run, it will execute some code, for example creating database and inserting test data. We’ll explore these options in the next blog post.