【问题标题】:How to moq HttpContext on Asp net Core如何在 Asp net Core 上最小起订量 HttpContext
【发布时间】:2019-11-21 10:27:45
【问题描述】:

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

我试试这个:

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

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

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

【问题讨论】:

标签: c# asp.net unit-testing asp.net-core xunit


【解决方案1】:

您可以使用ControllerContext 将上下文设置为DefaultHttpContext,您可以根据需要进行修改。

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

【讨论】:

  • 这个方法只得到public HttpContext HttpContext { get; }
  • 我这样设置:** var controller = new DashboardController() { ControllerContext = new Microsoft.AspNetCore.Mvc.ControllerContext()}; controller.ControllerContext.HttpContext = new DefaultHttpContext(); var resp = controller.MainDashboard(); **
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    经过一段时间后,我认为 moq 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***
    
    }
    

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

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

    【讨论】:

      猜你喜欢
      • 2022-11-15
      • 2017-07-26
      • 2021-08-22
      • 2021-07-11
      • 1970-01-01
      • 2018-05-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多