如何使用 Moq aspnetcore C# xUnit 模拟 ActionContext

How mock ActionContext with Moq aspnetcore C# xUnit

我正在尝试模拟这个控制器:

public IActionResult List()
{          

   Response.Headers.Add("contentRange", "1");
   Response.Headers.Add("acceptRange", "1");

   return Ok();
}

通过此测试:

[Fact]
public void when_call_list_should_return_sucess()
{
   //Arrange

   //Act
   var result = _purchaseController.List();

   //Assert
   Assert.Equal(200, ((ObjectResult)result).StatusCode);
}

但是我的HttpContext是null,报错了,怎么mock我的ActionContext和HttpContext来测试?

您可以在构建 _purchaseController 的地方、在您的设置中或类似的地方执行此操作。在您的情况下,您甚至不必模拟它。

_purchaseController = new PurchaseController
{
    ControllerContext = new ControllerContext 
    {
        HttpContext = new DefaultHttpContext()
    }
}

但如果您还想验证响应 header,您可能会同时模拟 HttpContext 和预期的 HttpResponse,并提供您自己的 HeaderDictionary验证。

_headers = new HeaderDictionary();

var httpResponseMock = new Mock<HttpResponse>();
httpResponseMock.Setup(mock => mock.Headers).Returns(_headers);

var httpContextMock = new Mock<HttpContext>();
httpContextMock.Setup(mock => mock.Response).Returns(httpResponseMock.Object);

_purchaseController = new PurchaseController
{
    ControllerContext = new ControllerContext 
    {
        HttpContext = httpContextMock.Object
    }
}

然后你可以在测试中断言 header collection

var result = _sut.List();

Assert.Equal("1", _headers["contentRange"]);
Assert.Equal("1", _headers["acceptRange"]);