【问题标题】:Mock HttpContext in web api using MOQ使用 MOQ 在 web api 中模拟 HttpContext
【发布时间】:2017-10-27 13:34:13
【问题描述】:

我正在尝试为 web api 控制器模拟 HttpContext 并使用 moq 并且在谷歌搜索后没有得到任何关于 web api 控制器的相关帖子,所以请帮助我。

var context = new Mock<HttpContextBase>();
            var request = new Mock<HttpRequestBase>();
            var response = new Mock<HttpResponseBase>();
            var session = new Mock<HttpSessionStateBase>();
            var server = new Mock<HttpServerUtilityBase>();

            context.Setup(c => c.Request).Returns(request.Object);
            context.Setup(c => c.Response).Returns(response.Object);
            context.Setup(c => c.Session).Returns(session.Object);
            context.Setup(c => c.Server).Returns(server.Object);


            return context.Object;

这种方式适用于 MVC,但不适用于 Web api,因为我们可以在 MVC 中将 HttpContextBase 传递给 ControllerContext,但不能在 Web API 中。

【问题讨论】:

  • 当前状态的问题不清楚,因为它不完整。阅读How to Ask,然后提供minimal reproducible example,可以用来更好地理解您的问题。
  • 同时停止将您的代码与HttpContext 紧密耦合,这是一个难以测试的实现问题。您可以通过正确构建代码来避免该问题。将HttpContext 视为第 3 方依赖项。
  • 也就是说,有没有办法在web api中模拟httpcontext而不作为外部依赖传递?
  • 视情况而定。您需要提供更多关于您正在尝试做的事情的背景信息。
  • 请检查问题是否明确。

标签: c# unit-testing asp.net-web-api moq


【解决方案1】:

我们对此有何看法?

public interface IHttpContext
{
    string Url { get; }
}

public class HttpContextProvider : IHttpContext
{
    public string Url => HttpContext.Current.Request.Url.ToString();
}

public class MockedHttpContextProvider : IHttpContext
{
    public string Url => "https://google.com";
}

我同意您不应该将 HttpContext 深入到您的应用程序中,但是如果您正在重构旧代码并且它已经沿树向下传递了很长一段路,我发现下面是为您的新代码编写单元测试的好方法代码,不必碰别人的东西!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-29
    • 1970-01-01
    • 1970-01-01
    • 2013-06-13
    • 2014-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多