【问题标题】:How mock ActionContext with Moq aspnetcore C# xUnit如何使用 Moq aspnetcore C# xUnit 模拟 ActionContext
【发布时间】:2017-08-06 22:21:42
【问题描述】:

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

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 来测试?

【问题讨论】:

    标签: c# unit-testing moq xunit


    【解决方案1】:

    您可以在您构建_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"]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-24
      • 2019-09-27
      • 1970-01-01
      • 2021-08-17
      • 2016-08-13
      • 2012-03-18
      • 2010-10-19
      • 2016-09-30
      相关资源
      最近更新 更多