How to Solve the XUnity Automated Test Error:
Castle.DynamicProxy.InvalidProxyConstructorArgumentsException
HResult=0x80070057
Message=Can not instantiate proxy of class: Database Context
Could not find a parameterless constructor.
Source=Castle.Core
StackTrace:
at Castle.DynamicProxy.ProxyGenerator.CreateClassProxyInstance(Type proxyType, List`1 proxyArguments, Type classToProxy, Object[] constructorArguments)
at Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, Object[] constructorArguments, IInterceptor[] interceptors)
at Moq.CastleProxyFactory.CreateProxy(Type mockType, IInterceptor interceptor, Type[] interfaces, Object[] arguments)
at Moq.Mock`1.InitializeInstance()
at Moq.Mock`1.OnGetObject()
at Moq.Mock.get_Object()
at Moq.Mock`1.get_Object()
Login to See the Rest of the Answer
Answer: When this error happens while testing an Asp.Net Core 3.1 using XUnit Testing Framework, make sure you include the default values when creating a Database Context Constructor. There is a parameter preventing the Instatietion of the DbContext (Database Context).
- Another way to resolve this is by creating an empty constructor in the DBContext Class, this way the instantiation of the DBContext class in XUnit Test Application won't throw an Error.
- However, if you want to use an existing DatabaseContext used in your Asp.Net Core 3.1 Application
when testing an Asp.Net Core 3.1 Controller using XUnit Testing Framework then see the example below:
namespace XUnit_Test_Project_For_AspNetCore_3_1
{
public class Pass_MyServiceRepository
{
[Fact]
public void Should_Pass_GetById()
{
int id = 6;
var imyinterface = new Mock<IMyInterface>();
//Database Configuration
var optionsBuilder = new DbContextOptionsBuilder<MyLovelyDBContextClass>();
optionsBuilder.UseSqlServer("Server=ServerName;Database=NameOfDatabaseHere;Persist Security Info=True;User ID=UserName;Password=SecurePassword;MultipleActiveResultSets=True;");
var mockSet = new Mock<DbSet<NameOfPocoModelClass>>();
var mockContext = new Mock<MyLovelyDBContextClass>(optionsBuilder);
mockContext.Setup(m => m.NameOfPocoModelClass).Returns(mockSet.Object);
using (var context = new MyLovelyDBContextClass(optionsBuilder.Options))
{
var service = new SearchRepository(context, IMyInterface.Object);
IEnumerable<NameOfPocoModelClass> list = service.GetById(id);
Assert.NotNull(list);
}
}
}
}