Search code examples
c#asp.net-core-6.0xunit.net

Unit testing a controller with parameterized constructor in xunit project using MOQ


I am trying to write a xunit test method for my controller to test a JsonResult. But since the controller takes a parameter which will be injected from DI container, I am not sure how and where to pass this parameter in my test method.

Controller:

public class AppGuidelinesController : Controller
{
    private IAppGuidelineBLRepository appGuidelineRepos;

    public AppGuidelinesController(IAppGuidelineDBRepository dataRepos)
    {
        appGuidelineRepos = new AppGuidelineBLRepository(dataRepos);
    }
}

Test method

[Fact]
public void GetJsonData_Returns_JsonResult()
{
    // Arrange
    Mock<IAppGuidelineDBRepository> dbReposMock = new Mock<IAppGuidelineDBRepository>();

    var appGuideline = new AppGuideline()
    {
        Id = 1
    };

    dbReposMock.Setup(repo => repo.AddGuideline(appGuideline));

    var controller = new AppGuidelinesController(dbReposMock.Object);

    var mockControllerContext = new Mock<ControllerContext>();
    controller.ControllerContext = mockControllerContext.Object;

    AppGuidelineRequestModel appGuidelineRequestModel = new AppGuidelineRequestModel()
    {
        Id = 1
    };

    OperationStatus expectedOperationStatus = new OperationStatus
    {
        StatusType = hrlib_test.Enums.StatusType.Success
    };

    // Act
    var result = controller.AddGuideline(appGuidelineRequestModel);


    // Assert
    Assert.NotNull(result);
    Assert.IsType<JsonResult>(result);

    var actualOperationStatus = result.Value as OperationStatus;
    Assert.NotNull(actualOperationStatus);
    Assert.Equal(expectedOperationStatus.StatusType, actualOperationStatus.StatusType);
}

When I run the test, I am getting the below error

System.ArgumentException : Constructor arguments cannot be passed for interface mocks.

Kindly help me to fix this issue and continue with other methods. Thank you.


Solution

  • Seems like I forgot to remove a piece of test code from the constructor which was causing the actual error instead of the test method. After I removed it, the test passed. I found some help from this link => Constructor arguments cannot be passed for interface mocks

    enter image description here