【问题标题】:can not pass httpcontextbase into method with HttpContext type variable无法将 httpcontextbase 传递给具有 HttpContext 类型变量的方法
【发布时间】:2012-05-01 17:39:04
【问题描述】:

我有方法期望 HttpContext 类型变量。

public string GetQueryStringValues(HttpContext context)

我正在从文章hanselman article 编写单元测试,使用 Moq 创建/填充 HttpContext 并按如下方式传递给方法:

        string url = "http://localhost:51209/WebForm1.aspx?height=6&width=7&length=8&mode=walk";
        HttpContextBase contextbase = MoqHelper.FakeHttpContext(url);
        string result = new Helper(whitelist).GetQueryStringValues(context); 

我收到以下错误消息:

无法从“System.Web.HttpContextBase”转换为“System.Web.HttpContext”

如何在不更改方法 GetQueryStringValues 的签名的情况下解决此问题??

请帮忙。

谢谢

【问题讨论】:

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


    【解决方案1】:

    很遗憾,您无法在不更改签名的情况下执行此操作。但是,您的签名使用抽象而不是具体类型会更好。

    【讨论】:

    • 您的方法需要更改为采用HttpContextBase 而不是HttpContext - 即:public string GetQueryStringValues(HttpContextBase context)
    • 抽象是指:HttpContextBase - 它是一个抽象类,HttpContext 是一个具体实现。
    • 写完单元测试后,我必须看看实际的asp.net网页是否能够将上下文对象传递给使用上下文库作为输入参数的方法。大家觉得呢?
    • 抽象有很多好处——它们可以被其他实现替代,你可以提供模拟实现(你的情况),你提供松耦合等等。底线是你会从中受益更改签名。
    • empi,在我的 asp.net 应用程序中,我使用 HttpContext.Current 获取上下文并传递给方法。如何获取 HttpContextBase 的实例?我做不到
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多