Question: I am unable to unit test one of my functions that contains `HttpContext.Current.Request.LogonUserIdentity.Name`

The error that I get is because `LogonUserIdentity` is null. 

I added this in my unit test in order to set a value for `HttpContext.Current` because that was also null:

```
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?
> 
> 
>

Answer: 
This is a sign of much bigger problem to come.

> 
> 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](https://msdn.microsoft.com/en-us/library/system.web.httprequest.logonuseridentity(v=vs.110).aspx#Anchor_2) ***(emphasis mine)***

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

You can't. Not in a unit test as IIS is not available.

Avoid tightly coupling your code to untestable code you cannot control like `HttpContext` and most of `System.Web` namespace. 

Instead, encapsulate them behind abstraction you control and can mock.
Not really the best mock, but sometimes you're trapped.

In this solution you must handle locally logged user (johndoe) on controller and/or 
in your db.

But works.

```
            var mockRequest = new HttpRequest("", "http://tempuri.org", "");
            HttpContext.Current = new HttpContext(
                mockRequest,
                new HttpResponse(new StringWriter())
            );

            mockRequest.GetType().InvokeMember(
                "_logonUserIdentity", 
                System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.SetField | System.Reflection.BindingFlags.Instance, 
                System.Type.DefaultBinder,
                mockRequest,
                new object[] { WindowsIdentity.GetCurrent() }
            );

```