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

我正在尝试模拟此控制器:

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为空,并且发生错误,我该如何模拟ActionContext和HttpContext进行测试?

解决方法:

您可以在安装程序等中构造_purchaseController的地方执行此操作.在您的情况下,您甚至不必嘲笑它.

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

但是,如果您还想验证响应头,则可能会同时模拟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
    }
}

然后可以在测试中声明标头集合

var result = _sut.List();

Assert.Equal("1", _headers["contentRange"]);
Assert.Equal("1", _headers["acceptRange"]);
上一篇:使用xUnit为.net core程序进行单元测试(上)


下一篇:使用 xUnit 编写 ASP.NET Core 单元测试