Reputation: 43
I am trying mock this controller:
public IActionResult List()
{
Response.Headers.Add("contentRange", "1");
Response.Headers.Add("acceptRange", "1");
return Ok();
}
With this test:
[Fact]
public void when_call_list_should_return_sucess()
{
//Arrange
//Act
var result = _purchaseController.List();
//Assert
Assert.Equal(200, ((ObjectResult)result).StatusCode);
}
But my HttpContext is null, and an error occurs, how could I mock my ActionContext and HttpContext to test?
Upvotes: 4
Views: 4881
Reputation: 250
You could do this where you construct your _purchaseController, in your Setup or the like. In your case you don't even have to mock it.
_purchaseController = new PurchaseController
{
ControllerContext = new ControllerContext
{
HttpContext = new DefaultHttpContext()
}
}
But if you also want to verify the response headers you would probably mock both the HttpContext
and the expected HttpResponse
, and provide your own HeaderDictionary
to verify.
_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
}
}
Then you could Assert the header collection in a test
var result = _sut.List();
Assert.Equal("1", _headers["contentRange"]);
Assert.Equal("1", _headers["acceptRange"]);
Upvotes: 7