简体   繁体   中英

How to unit test a [System.Web.Http.Authorize] filter in ASP.net with Xunit

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM