c# - 如何对 "HttpContext.Current.Request.LogonUserIdentity.Name"进行单元测试?

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

我无法对包含 HttpContext.Current.Request.LogonUserIdentity.Name

的函数进行单元测试

我收到的错误是因为 LogonUserIdentity 为空。

我在单元测试中添加了这个,以便为 HttpContext.Current 设置一个值,因为它也是空的:

HttpContext.Current = new HttpContext(
            new HttpRequest("", "http://localhost:8609", ""),
            new HttpResponse(new StringWriter())
            );

How can I assign a value to LogonUserIdentity so that I can test my function?

最佳答案

这预示着更大的问题即将来临。

The LogonUserIdentity property exposes the properties and methods of the WindowsIdentity object for the currently connected user to Microsoft Internet Information Services (IIS). The instance of the WindowsIdentity class that is exposed by LogonUserIdentity tracks the IIS request token and provides easy access to this token for the current HTTP request being processed inside of ASP.NET. An instance of the WindowsIdentity class is automatically created so it does not need to be constructed to in order to gain access to its methods and properties.

Source (强调我的)

How can I assign a value to LogonUserIdentity so that I can test my function?

你不能。不在单元测试中,因为 IIS 不可用。

避免将您的代码与无法控制的不可测试代码紧密耦合,例如 HttpContext 和大多数 System.Web 命名空间。

相反,将它们封装在您可以控制和模拟的抽象之后。

关于c# - 如何对 "HttpContext.Current.Request.LogonUserIdentity.Name"进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51565544/

相关文章:

c# - XML 中的 Xamarin Android 比例位图

c# - 如何使用多态避免 'If cascade' 和类型转换?

matlab - 如何使内部/辅助函数可测试?

c# - 如何使用 Moq 模拟 SoapException 以单元测试错误处理

java - 使用 Maven 跳过 Jhipster 中的 Java 测试进行构建

c# - EF BulkInsert 未在 Task.Run() 中触发

c# - Include 返回的 Entity Framework 限制属性

c# - Azure 无法将消息添加到队列

javascript - 选择选项的一个值后 Controller 响应

使用 Microsoft 帐户的 C# Web api 身份验证