How To Get AutoFixtures AutoData Property To Work With NUNit

I've previously written about my love for Autofixture and how I'd recommend that you start using it on your project to make you drastically reduce the amount of unit testing set-up code you'll need to write.  I tend to use NUnit on projects (with a low move over to xUnit), however, when working with Autofixture I bumped into a few issues getting the AutoData property to work with NUnit within 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 tutorial's 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 out instead, but if you're working on a legacy project, or you just don't fancy xUnit, read on.

How To Get Autofixtures AutoData feature to work with NUnit


Ok, so before we start, 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 this and trying out the nifty Autodata attribute, I still got the 'AutoData no arguments provided'. Reading the AutoDataConnector, it mentioned adding an extra custom attribute 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:

 using AutoDataConnector;

    using Ploeh.AutoFixture;
    using Ploeh.AutoFixture.AutoMoq;

    public class AutoMoqDataAttribute : AutoDataAttribute
    {
        public AutoMoqDataAttribute()
            : base(
                new ParameterValueProvider(
                    new AutoFixtureDataProvider(
                        new AutoMoqCustomization(),
                        new MultipleCustomization())))
        {
        }
    }

To auto-populate my tests, I can now use the 'AutoMoqDataAttribute' attribute like so:

        [Test, AutoMoqData]
        public void TestAuthourForNull(MyClass myClass)
        {
            var prePolulatedObject = logger;
        }

I'm not sure if it was me doing something stupid, but if you find yourself in a similar situation, this will get you up and running, enjoy!

submit to reddit

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

Back to top