0

I need to check the ModelState of controller method which has AUTHORIZE filter, because of that it is not accessible.

    [Microsoft.AspNetCore.Mvc.Produces("application/json")]
    [System.Web.Http.Authorize]
    public Microsoft.AspNetCore.Mvc.ActionResult<HttpResponseMessage> CrowdSourcedData([FromBody] List<Apps> Apps)
    {
        if (!ModelState.IsValid)
        {
            return null;
        }
        return _dataProcessor.CrowdSourcedData(Apps);
    }

How can I unit test this method, I have tried other given options but nothing worked and I don't want to do Integration testing.

2

1 Answer 1

0

Here are a couple simple tests you can try:

[Fact]
public void CrowdSourcedData_Valid()
{
    // Arrange
    var message = new HttpResponseMessage();
    var apps = new List<Apps>();
    var dataProcessor = new Mock<IDataProcessor>(); // Assuming "IDataProcessor" or something
    dataProcessor.Setup(x => x.CrowdSourcedData(apps)).Returns(message);
    var controller = new Controller(dataProcessor.Object); // Assuming you inject the "_dataProcessor" here

    // Act
    var result = controller.CrowdSourcedData(apps);

    // Assert
    dataProcessor.Verify(x => x.CrowdSourcedData(apps), Times.Once);
    Assert.Equal(message, result);
}

[Fact]
public void CrowdSourcedData_Invalid()
{
    // Arrange
    var message = new HttpResponseMessage();
    var apps = new List<Apps>();
    var dataProcessor = new Mock<IDataProcessor>();
    dataProcessor.Setup(x => x.CrowdSourcedData(apps)).Returns(message);
    var controller = new Controller(dataProcessor.Object);
    controller.ModelState.AddModelError("FakeError", "FakeMessage"); // Here you set the invalid "ModelState"

    // Act
    var result = controller.CrowdSourcedData(apps);

    // Assert
    dataProcessor.Verify(x => x.CrowdSourcedData(apps), Times.Never);
    Assert.Null(result);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much it worked. I am new to this that's why I got confused. many many Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.