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: 
I spent a lot of time trying to mock HttpContext or HttpContextBase, then trying to shim with fakes WindowsIdentity class or HttpRequest.LogonUserIdentity property.
Nothing works - you don't need completely mocked HttpContext because you want see real responses, not your mock set ups returned. 
Shims are just not generating for WindowsIdentity class ("due to internal limitations") and for LogonUserIdentity property (no reason given in fakes messages, it's just not there).

The best approach how to get testable HttpContext with request and response is described here:
<http://jonlanceley.blogspot.com/2015/08/unit-testing-part-2-faking-httpcontext.html>

I was able to override LogonUserIdentity property in my fake request wrapper and set there whatever I need.
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() }
            );

```