Can not instantiate proxy of class

33 Views Asked by At

To test my controller project, I created an xUnit project and wrote a function and decorated it with the Fact attribute:

        [Fact]
        public void GetAllTest()
        {
            var mockMediator = new Mock<Mediator>();
            var controller = new ResidenceController(mockMediator.Object);
            var result = controller.GetAll();
            Assert.IsType<IEnumerable<ResidenceDto>>(result.Result);
            
        }

When I run this test get error:

Can not instantiate proxy of class: MediatR.Mediator. Could not find a parameterless constructor. (Parameter 'constructorArguments') ---- System.MissingMethodException : Constructor on type 'Castle.Proxies.MediatorProxy' not found.

My controller inherits from a custom API controller. Within the methods, I use MediatR to send commands.

1

There are 1 best solutions below

0
quyentho On

You are not showing your ResidenceController but I believe your problem is because you are using concrete implementation of Mediator class instead of the IMediator.

In ResidenceController:

private IMediator mediator;
public ResidenceController(IMediator mediator)
{
    this.mediator = mediator
}

In Program.cs:

services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining<Startup>());

Then in your test:

[Fact]
public void GetAllTest()
{
    var mockMediator = new Mock<IMediator>();
    var controller = new ResidenceController(mockMediator.Object);
    var result = controller.GetAll();
    Assert.IsType<IEnumerable<ResidenceDto>>(result.Result);
}

Please refer to the official documentation for more detail