Mock HttpContext for unit testing a .NET core MVC controller?

匿名 (未验证) 提交于 2019-12-03 08:28:06

问题:

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.

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?

回答1:

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 recieves the http header key value pair device-id:20317     ... } 


回答2:

Rather than mocking out the HTTPContext, it is probably a better idea to map the header into a parameter on the method. For example, in the controller at the bottom of this answer, the id parameter is set to the value header with a name equal to "device-id"... The unit test then becomes

[TestMethod] public void TestValuesController() {     ValuesController controller = new ValuesController();     var result = controller.GetHeaderValue("27");     Assert.AreEqual(result, "27"); } 

While you can mock the HttpContext, in my opinion it is something that should be avoided unless you have no choice. The documentation for the FromHeaderAttribute can be found here FromHeaderAttribute Class.

    public class ValuesController: Controller     {        public string GetHeaderValue([FromHeader(Name = "device-id")] string id)       {         return id;       }     } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!