I am creating an integration test for an API controller that requires custom header information in the request.
CONTROLLER
public IActionResult Delete([FromQuery] string param1, [FromQuery] string param2)
{
…
var id = Request.Headers["X-Id1"].ToString();
var id2 = Request.Headers["X-Id2"].ToString();
…
}
How can I add this request headers in my integration test? I got stuck at the code below because _controller.ControllerContext
is of type ControllerContext
and I cannot convert an HttpControllerContext
object to it. The error message is Cannot implicitly convert type 'System.Web.Http.Controllers.HttpControllerContext' to 'Microsoft.AspNetCore.Mvc.ControllerContext'
INTEGRATION TEST
[TestMethod]
public void Test()
{
var request = new HttpRequestMessage();
request.Headers.Add("X-Id1", "1");
request.Headers.Add("X-Id2", "2");
var controllerContext = new HttpControllerContext();
controllerContext.Request = request;
_controller.ControllerContext = controllerContext; // Error message shows here.
_controller.Delete("a", "b");
// Assertion here.
}
Is there another way to do this?
Try this code
_controller.ControllerContext.HttpContext = new DefaultHttpContext();
_controller.ControllerContext.HttpContext.Request.Headers["X-Id1"] = "1";
_controller.ControllerContext.HttpContext.Request.Headers["X-Id2"] = "2";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With