I've previously written about my love for Autofixture and why I recommend that you start using it within your project to help reduce the amount of boilerplate unit testing code that you will need to write (article found here). My testing framework of choice is usually NUnit, with a slow move over to xUnit. When working with Autofixture I bumped into a few issues getting the AutoData
property to work with NUnit while using the Resharper test harness. If you find yourself in a similar situation (or you want to auto-inject interfaces with pre-populated data), then this is the tutorial for you.
Tip: If you look at the Autofixture documentation, it seems to have been written with xUnit in mind. I'd recommend that you try xUnit as you should be able to copy and paste code straight from the documentation!
How To Get Autofixtures AutoData feature to work with NUnit
Ok, so before we start I should admit. Technically I never actually got this working. Instead, I ended up creating a custom Moq attribute that works with Autofixture to achieve the same result. I won't take the credit for this, as most of the code is based on, AutoFixture.NUnit3.AutoDataConnector. As the link implies, to get the AutoData to work you will need to install yet another Nuget package, AutoFixture.NUnit3.AutoDataConnector.
After installing AutoDataConnectorand trying out the nifty Autodata
attribute, I still got an error:
AutoData no arguments provided
After reading the AutoDataConnector, it mentioned adding an extra custom attribute that is required in order to get Autofixture working with interfaces. As most of my projects are heavily interface based, I did that. For reference the code for the attribute looks like this:
To auto-populate my tests that use interfaces, I can now use the AutoMoqDataAttribute
attribute like so:
Addin this attribute will now allow you to auto-create fixtures while using NUnit with mocked interfaces. Happy Coding 🤘