如何在 Asp.net Core 中使用 Moq 模拟 HttpContext

4

我有一个asp .net core项目,在几乎每个操作中我们都使用session,我的问题是如果我没有sessionRepository,如何进行测试。控制器测试会崩溃,因为控制器中的session为null。我尝试使用Moq IHttpContextAcessor,但也不起作用。

我尝试了以下代码:

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

但是HttpContext并不包含Current的定义。(使用Microsoft.AspNetCore.Http)

有没有办法模拟或测试使用HttpContext和会话的控制器?


1
这个回答解决了你的问题吗?如何在ASP.net Core单元测试项目中模拟Session变量? - ColinM
谢谢,我会尝试这个。 - BASKA
我在设置HttpContext时出现了问题,但是现在在控制器中遇到异常: 该应用程序或请求未配置Session。 - BASKA
3个回答

12
您可以使用ControllerContext来设置上下文为DefaultHttpContext,您可以根据需要进行修改。
var ctx = new ControllerContext() { HttpContext = new DefaultHttpContext()};
var tested = new MyCtrl();
tested.ControllerContext = ctx;

这个方法只是获取public HttpContext HttpContext { get; } - BASKA
2
我是这样设置的: ** var controller = new DashboardController() { ControllerContext = new Microsoft.AspNetCore.Mvc.ControllerContext()}; controller.ControllerContext.HttpContext = new DefaultHttpContext(); var resp = controller.MainDashboard(); ** - BASKA

1
控制器有一个控制器上下文,您可以设置它(我使用默认值):
Controller.ControllerContext = new ControllerContext                                                
{
    HttpContext = new DefaultHttpContext()
};

0

经过一段时间的思考,我认为模拟Session是一个不好的想法,更好的方法是创建一个IOC容器。例如,我们可以创建一个ISessionManager接口,其中包含返回存储在会话中的对象的方法:

public class SessionManager:ISessionManager{

public User GetUser(){
  User usr= JsonConvert.DeserializeObject<User>(HttpContext.Session.GetString("USER"));
  return usr;
}

***here we get data from session***

}

对于单元测试,我们只需创建一个实现ISessionManager接口的新类,并将其用于测试控制器。

public class SessionManagerTest:ISessionManager{

public User GetUser(){
  User usr=new User();
  ...initialize all fields
  return usr;
}
******
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接