用于单元测试 .NET 核心 MVC 控制器的模拟 HttpContext?

用于单元测试 .NET 核心 MVC 控制器的模拟 HttpContext?

问题描述:

我在控制器中有一个函数,我正在对它进行单元测试,它需要 http 请求的标头中的值.我无法初始化 HttpContext 因为它是只读的.

I have a function in a controller that I am unit testing that expects values in the header of the http request. I can't initialize the HttpContext because it is readonly.

我的控制器函数需要device-id"的 http 请求标头值

My controller function expects a http request header value for "device-id"

[TestMethod]
public void TestValuesController()
{
    ValuesController controller = new ValuesController();

    //not valid controller.HttpContext is readonly
    //controller.HttpContext = new DefaultHttpContext(); 

    var result = controller.Get();
    Assert.AreEqual(result.Count(), 2);
}

是否有一种直接的方法可以在不使用第三方库的情况下做到这一点?

Is there a straight-forward way to do this without using a third party library?

我能够以这种方式初始化 httpcontext 和标头:

I was able to initialize the httpcontext and header in this way:

[TestMethod]
public void TestValuesController()
{
    ValuesController controller = new ValuesController();
    controller.ControllerContext = new ControllerContext();
    controller.ControllerContext.HttpContext = new DefaultHttpContext();
    controller.ControllerContext.HttpContext.Request.Headers["device-id"] = "20317";
    var result = controller.Get();
    //the controller correctly receives the http header key value pair device-id:20317
    ...
}