AutoFixture customization for ASP.Net Core Web API controller

Lets start with simple controller:

public class TestController : Controller
	public IActionResult Get()
		return Ok();

Now we want to create unit test for this method using AutoFixture/Moq/Shouldly/XUnit stack:

public class TestControllerTests 
	[Theory, AutoMoqData]
	public void Get_ShouldReturn_HttpStatusOk(TestController sut)
		// act..
		var actual = sut.Get();

		// assert..

Test runner will crash saying:

AutoFixture.ObjectCreationException : AutoFixture was unable to create an instance from Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary because creation unexpectedly failed with exception. Please refer to the inner exception to investigate the root cause of the failure.

Request path:
	  J2BI.Holidays.TravelDocs.Api.Controllers.AccommodationController sut --> 
	   J2BI.Holidays.TravelDocs.Api.Controllers.AccommodationController --> 
	    Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary ViewData --> 

---- System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation.
-------- Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can not instantiate proxy of class: Microsoft.AspNetCore.Mvc.ModelBinding.ModelMetadata.
Could not find a parameterless constructor.

The problem lies in lack of parameterless constructor for ModelMetadata class.
This can easily be fixed with AutoFixture customization:

public class ApiControllerCustomization : ICustomization
    public void Customize(IFixture fixture)
        fixture.Register(() => new CustomCompositeMetadataDetailsProvider());
        fixture.Inject(new ViewDataDictionary(fixture.Create(), fixture.Create()));

    private class CustomCompositeMetadataDetailsProvider : ICompositeMetadataDetailsProvider
        public void CreateBindingMetadata(BindingMetadataProviderContext context)
            throw new System.NotImplementedException();

        public void CreateDisplayMetadata(DisplayMetadataProviderContext context)
            throw new System.NotImplementedException();

        public void CreateValidationMetadata(ValidationMetadataProviderContext context)
            throw new System.NotImplementedException();

This now has to be wrapped in data attribute:

public class AutoApiMoqDataAttribute : AutoDataAttribute
    public AutoApiMoqDataAttribute()
        : base(() =>
            var fixture = new Fixture();

            fixture.Customize(new ApiControllerCustomization())
                   .Customize(new AutoMoqCustomization())
                   .Behaviors.Add(new OmitOnRecursionBehavior());

            return fixture;

Voila! Now the test will pass.

Check out this gist

Unit Testing stack for C#/Visual Studio

After spending some time on digging through unit testing components, I ran into a setup I am finally happy with. This consists of: – acts as DI container/object factory, significantly improving unit test maintainability – awesome mocking framework, fully integrated with AutoFixture – excellent utility for comparing instances – great for simplifying assertion statements – superb unit testing framework, supporting parameterized tests, multiple test executions and much more

Although each utility is great on it’s own, when combined together, this stack significantly reduces amount of testing code.

Below I include sample config file with latest versions of all packages.

<?xml version="1.0" encoding="utf-8"?>
    <package id="AutoFixture" version="3.50.2" targetFramework="net461" />
    <package id="AutoFixture.AutoMoq" version="3.50.2" targetFramework="net461" />
    <package id="AutoFixture.Idioms" version="3.50.2" targetFramework="net461" />
    <package id="AutoFixture.Xunit2" version="3.50.2" targetFramework="net461" />
    <package id="Moq" version="4.1.1308.2120" targetFramework="net461" />
    <package id="SemanticComparison" version="3.50.2" targetFramework="net461" />
    <package id="Shouldly" version="2.8.2" targetFramework="net461" />
    <package id="xunit" version="2.1.0" targetFramework="net461" />
    <package id="xunit.abstractions" version="2.0.0" targetFramework="net461" />
    <package id="xunit.assert" version="2.1.0" targetFramework="net461" />
    <package id="xunit.core" version="2.1.0" targetFramework="net461" />
    <package id="xunit.extensibility.core" version="2.1.0" targetFramework="net461" />
    <package id="xunit.extensibility.execution" version="2.1.0" targetFramework="net461" />
    <package id="xunit.runner.visualstudio" version="2.1.0" targetFramework="net461" />