C# 如何使用 Moq 在 ASP.NET MVC 中模拟 HttpContext?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1452418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 17:41:20  来源:igfitidea点击:

How do I mock the HttpContext in ASP.NET MVC using Moq?

c#asp.net-mvcmockingmoqhttpcontext

提问by Geo

[TestMethod]
public void Home_Message_Display_Unknown_User_when_coockie_does_not_exist()
{
    var context = new Mock<HttpContextBase>();
    var request = new Mock<HttpRequestBase>();
    context
        .Setup(c => c.Request)
        .Returns(request.Object);
    HomeController controller = new HomeController();

    controller.HttpContext = context; //Here I am getting an error (read only).
    ...
 }

my base controller has an overrride of the Initialize that get's this requestContext. I am trying to pass this along but I am not doing something right.

我的基本控制器覆盖了获取此 requestContext 的 Initialize。我试图传递这个,但我没有做正确的事情。

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
    base.Initialize(requestContext);
}

Where can I get more information on mocking my RequestContext and HttpContext using Moq? I am trying to mock cookies and the general context.

在哪里可以获得有关使用 Moq 模拟 RequestContext 和 HttpContext 的更多信息?我正在尝试模拟 cookie 和一般上下文。

回答by tvanfosson

HttpContext is read-only, but it is actually derived from the ControllerContext, which you can set.

HttpContext 是只读的,但它实际上是从 ControllerContext 派生的,您可以设置它。

 controller.ControllerContext = new ControllerContext( context.Object, new RouteData(), controller );

回答by 0100110010101

Create a request, response and put them both to HttpContext:

创建一个请求、响应并将它们都放到 HttpContext 中:

HttpRequest httpRequest = new HttpRequest("", "http://mySomething/", "");
StringWriter stringWriter = new StringWriter();
HttpResponse httpResponse = new HttpResponse(stringWriter);
HttpContext httpContextMock = new HttpContext(httpRequest, httpResponse);

回答by Dinis Cruz

Here is an example of how you can set this up: Mocking HttpContext HttpRequest and HttpResponse for UnitTests (using Moq)

以下是如何设置的示例:Mocking HttpContext HttpRequest 和 HttpResponse for UnitTests (using Moq)

Note the extension methods which really help to simplify the usage of this mocking classes:

请注意真正有助于简化此模拟类使用的扩展方法:

var mockHttpContext = new API_Moq_HttpContext();

var httpContext = mockHttpContext.httpContext();

httpContext.request_Write("<html><body>".line()); 
httpContext.request_Write("   this is a web page".line());  
httpContext.request_Write("</body></html>"); 

return httpContext.request_Read();

Here is an example of how to write a Unit Test using moq to check that an HttpModule is working as expected: Unit Test for HttpModule using Moq to wrap HttpRequest

以下是如何使用 moq 编写单元测试以检查 HttpModule 是否按预期工作的示例:使用 Moq 包装 HttpRequest 的 HttpModule 单元测试

Update: this API has been refactored to

更新:此 API 已重构为

回答by Xolartek

Here's how I used the ControllerContext to pass a fake Application path:

下面是我如何使用 ControllerContext 来传递一个虚假的应用程序路径:

[TestClass]
public class ClassTest
{
    private Mock<ControllerContext> mockControllerContext;
    private HomeController sut;

    [TestInitialize]
    public void TestInitialize()
    {
        mockControllerContext = new Mock<ControllerContext>();
        sut = new HomeController();
    }
    [TestCleanup]
    public void TestCleanup()
    {
        sut.Dispose();
        mockControllerContext = null;
    }
    [TestMethod]
    public void Index_Should_Return_Default_View()
    {

        // Expectations
        mockControllerContext.SetupGet(x => x.HttpContext.Request.ApplicationPath)
            .Returns("/foo.com");
        sut.ControllerContext = mockControllerContext.Object;

        // Act
        var failure = sut.Index();

        // Assert
        Assert.IsInstanceOfType(failure, typeof(ViewResult), "Index() did not return expected ViewResult.");
    }
}

回答by Chandan Kumar

Thanks user 0100110010101.

感谢用户 0100110010101。

It worked for me and here i had an issue while writing the testcase for the below code :

它对我有用,在这里我在为以下代码编写测试用例时遇到了问题:

 var currentUrl = Request.Url.AbsoluteUri;

And here is the lines which solved the problem

这是解决问题的线路

HomeController controller = new HomeController();
//Mock Request.Url.AbsoluteUri 
HttpRequest httpRequest = new HttpRequest("", "http://mySomething", "");
StringWriter stringWriter = new StringWriter();
HttpResponse httpResponse = new HttpResponse(stringWriter);
HttpContext httpContextMock = new HttpContext(httpRequest, httpResponse);
controller.ControllerContext = new ControllerContext(new HttpContextWrapper(httpContextMock), new RouteData(), controller);

Might be helpful for the others.

可能对其他人有帮助。