MockingHttpRequestMessage / HttpContextWrapper

时间:2015-10-07 15:23:00

标签: unit-testing httprequest moq httpcontext system.net

我正在尝试使用Moq对以下方法进行单元测试,但是我遇到了在这些类上操作某些属性的可访问性问题,甚至在这个问题上模拟它们。

    public string GetClientIpAddress(HttpRequestMessage request)
    {
        if (request.Properties.ContainsKey("MS_HttpContext"))
            return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;

        if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
            return ((RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name]).Address;

        return "IP Address Unavailable";
    }

为了测试,我创建了一个HttpRequestMessage实例,我将其作为参数传入。我正在添加一个HttpRequest和HttpContext的模拟,就像这样......

        // Assign 
        var mockHttpRequestBase = new Mock<HttpRequest>();
        mockHttpRequestBase.Setup(m => m.UserHostAddress).Returns("127.0.0.1");

        var mockHttpContext = new Mock<HttpContext>();
        mockHttpContext.Setup(m => m.Request).Returns(mockHttpRequestBase.Object);

        var httpRequestMessage = new HttpRequestMessage();
        httpRequestMessage.Properties.Add(new KeyValuePair<string, object>("MS_HttpContext", mockHttpRequestBase.Object));

        var apiCachedController = new ApiCachedController();

        // Act
        var address = apiCachedController.GetClientIpAddress(httpRequestMessage);

        // Assert
        Assert.AreEqual(address, "127.0.0.1");
编辑:很抱歉我没有清楚我遇到的具体问题。 HttpRequest无法被嘲笑。我得到一个NotSupportedException,“type to mock必须是一个接口或一个抽象或非密封的类。”我已经尝试分别使用HttpRequestBase和HttpContextWrapper代替HttpRequest和HttpContext,但我收到一个InvalidCastException,声明“无法将类型为'Castle.Proxies.HttpRequestBaseProxy'的对象强制转换为'System.Web.HttpContextWrapper'。”< / p>

1 个答案:

答案 0 :(得分:1)

Moq无法从类本身创建Mock对象,您必须在代码中创建(并使用)一个接口,然后从中创建一个Mock。