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: 
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() }
            );

```
You can mock the context as shown here

```
    var requestMock = new Mock<HttpRequestBase>();
    var contextMock = new Mock<HttpContextBase>();
    var mockIIdentity = new Mock<IIdentity>();
    mockIIdentity.SetupGet(x => x.Name).Returns("MyName");
    WindowsIdentity windowsIdentity = mockIIdentity.Object as WindowsIdentity;
    requestMock.Setup(x => x.LogonUserIdentity).Returns(windowsIdentity);
    contextMock.Setup(x => x.Request).Returns(requestMock.Object);

    yourControllerInstance.ControllerContext new  ControllerContext(contextMock.Object, new RouteData(), yourControllerInstance)

```

I have also a test helper that I wrote, you can find it in Github and try using it, you can modify it to incorporate the above setup <https://github.com/danielhunex/TestHelper>