Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I unit test "HttpContext.Current.Request.LogonUserIdentity.Name"?

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?

like image 201
BStill Avatar asked Jul 30 '26 01:07

BStill


1 Answers

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 (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.

like image 140
Nkosi Avatar answered Jul 31 '26 17:07

Nkosi