如何在 Asp net Core 上最小化 HttpContext

How to moq HttpContext on Asp net Core

我有一个 asp .net 核心项目,实际上在我们使用会话的每个操作中,我的问题是如果我没有 sessionRepository 如何测试它。控制器测试 crush,因为控制器中的会话为空。我尝试 Moq IHttpContextAcessor 但它也不起作用。

我试试这个:

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

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

有什么方法可以最小起订量或测试使用 HttpContext 和会话的控制器吗?

控制器有一个你可以设置的控制器上下文(我使用默认的):

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

您可以使用 ControllerContext to set the context to be DefaultHttpContext,您可以根据需要进行修改。

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

一段时间后,我认为对 moq Session 来说是个坏主意,更好的方法是创建一个 IOC 容器,例如我们创建 ISessionManager 接口,方法 return 存储在会话对象中:

public class SessionManager:ISessionManager{

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

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

}

对于 UnitTest,我们只是创建了一个新的 class,它实现了 ISessionManager 并将其用于测试控制器。

public class SessionManagerTest:ISessionManager{

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