We are attempting to create a simple unit test for our ASP.Net Core API controllers. We are using autofixture with autoMoq, XUnit2, and shoudly. How do we mock the TypeInfo creation? Or is there a better approach?
We followed this post to resolve the initial error of:
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.
namespace Tests.Controllers
{
using Api.Controllers;
using AutoFixture;
using AutoFixture.AutoMoq;
using Shouldly;
using System.Threading.Tasks;
using Xunit;
public class DiagnosticControllerTests
{
private readonly DiagnosticController _sut;
public DiagnosticControllerTests()
{
var fixture = new Fixture();
fixture.Customize(new AutoMoqCustomization())
.Customize(new ApiControllerCustomization()); // from Matt Uliasz see link above
_sut = fixture.Create<DiagnosticController>();
}
[Fact]
public async Task Ping_Returns_True()
{
var actual = await _sut.Ping();
actual.Data.ShouldBe(true);
}
}
}
This is throwing the following errors:
AutoFixture.ObjectCreationExceptionWithPath AutoFixture was unable to create an instance from System.Reflection.TypeInfo because creation unexpectedly failed with exception. Please refer to the inner exception to investigate the root cause of the failure. ... Inner exception messages: Castle.DynamicProxy.InvalidProxyConstructorArgumentsException: Can not instantiate proxy of class: System.Reflection.TypeInfo. Could not find a parameterless constructor.
Edit After further testing, the error disappears when we stop deriving from the class Microsoft.AspNetCore.Mvc.Controller.
namespace Api.Controllers
{
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Models;
using System.Threading.Tasks;
[Authorize]
[Route("api/[controller]")]
public class DiagnosticController: Controller
{
[AllowAnonymous]
[HttpGet]
[Route("ping")]
public Task<PingResultDto> Ping()
{
var result = new PingResultDto
{
Data = true
};
return Task.FromResult(result);
}
}
}
Edit 2 Our current work-around is to not use AutoFixture/AutoMoq:
var sut = new Mock<DiagnosticController>().Object; //This works