我在单元测试的控制器中有一个函数,该函数期望http请求的标头中的值。我无法初始化HttpContext,因为它是只读的。
我的控制器函数期望“ device-id”的http请求标头值为
[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); }
有没有使用第三方库的简单方法?
我能够以这种方式初始化httpcontext和标头:
[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 ... }