c# - 访问类中的模拟 Request.ServerVariables

标签 c# mocking request.servervariables

我模拟了 Controller 中使用的服务器变量。

request.SetupGet(x => x.ServerVariables)
    .Returns(new System.Collections.Specialized.NameValueCollection
    {
        {"SERVER_NAME","localhost"}, 
        {"SCRIPT_NAME","localhost"}, 
        {"SERVER_PORT","80"}, 
        {"HTTPS","www.melaos.com"}, 
        {"REMOTE_ADDR","127.0.0.1"}, 
        {"REMOTE_HOST","127.0.0.1"} 
    });

我可以在 Controller 中获取服务器变量的值,但不能在模型类中获取。为什么会这样?

在Controller和Model中获取值的唯一区别是,在Controller中我们编写HttpContext.Request.ServerVariables,而在Model中我们编写HttpContext.Current.Request.ServerVariables >.

它们有什么不同吗?我怎样才能在模型中获取这些值。

最佳答案

while in Model we write HttpContext.Current.Request.ServerVariables.

HttpContext.Current 是问题所在。它是一个静态属性,无法模拟,也无法在 ASP.NET 上下文(例如单元测试)之外使用。因此,如果您使用 HttpContext.Current,则无法对您的应用程序进行单元测试。也就是说,您不应该在模型中使用任何 HTTP 特定的工件。您应该直接将值从 Controller 传递到模型,以便模型不会尝试获取它们。

关于c# - 访问类中的模拟 Request.ServerVariables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8383554/

相关文章:

c# - 为什么我应该避免在 C# 中使用 Properties?

unit-testing - PHPUnit 和接缝

java - Mockito:返回传递的参数

asp.net - Request.ServerVariables ["REMOTE_ADDR"]足够可靠吗?

phpunit - 如何使用 Symfony3 在 PHPUnit 测试用例中填充/模拟服务器变量?

asp.net-core - 如何在AspnetCore 1.0中访问ServerVariables

c# - 如何从我的 ASP.NET Core 应用程序中永久注销用户?

c# - 将网站转换为 Html 到 Excel

用于大量条目的 C# LazyList

perl - 我怎样才能在另一个模块中模拟一个子模块?