How to moq HttpContext on Asp net Core

拜拜、爱过 提交于 2020-06-29 05:29:07

问题


I have an asp .net core project, and practically in each action we use session, my question is how to test it if I don't have sessionRepository. Controller tests crush because session in controller is null. I try to Moq IHttpContextAcessor and it also doesn't work.

I try this:

HttpContext.Current = new HttpContext(new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null));

but HttpContext doesn't contain the definition for Current. (using Microsoft.AspNetCore.Http;)

Is there any way to moq or test controllers that use HttpContext and sessions?


回答1:


You can use ControllerContext to set the context to be DefaultHttpContext which you can modify to your needs.

var ctx = new ControllerContext() { HttpContext = new DefaultHttpContext()};
var tested = new MyCtrl();
tested.ControllerContext = ctx;



回答2:


The controller has an Controller context which you can set (i used the default one) :

Controller.ControllerContext = new ControllerContext                                                
{
    HttpContext = new DefaultHttpContext()
};


来源:https://stackoverflow.com/questions/58972693/how-to-moq-httpcontext-on-asp-net-core

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