Josh
Josh

Reputation: 8477

How set HttpContext.Current.User.Identity.Name for Unit Testing

Background:

I'm testing a function within an ASP.NET 4.0 (Web Forms not MVC) and I'm using Unit Testing built into Visual Studio 2010. I've created a separate test project and creating a test class for each class in the web project.

Question:

I've run into an issue with one of the functions that uses HttpContext.Current.User.Identity.Name as part of the logic. How do set that value in the Unit testing project class or method so that I can test that function?

Update:

What I was hoping for was that there was additional attribute I could set above my test method. Currently I have:

[TestMethod()]
[HostType("ASP.NET")]
[AspNetDevelopmentServerHost("C:\\DEV\\ProjectName\\ClientWeb", "/")]
[UrlToTest("http://localhost:9018/")]
public void GetLoginTest()
{
  // test code
}

Upvotes: 3

Views: 4528

Answers (2)

Red Taz
Red Taz

Reputation: 4179

You could create your own Principal by implementing IPrincipal, within that you'd need to define a custom Identity using the IIdentity interface, inside which you'd return your value for the Name property.

You could then set HttpContext.Current.User to your custom Principal object.

Upvotes: 1

Dirk Brockhaus
Dirk Brockhaus

Reputation: 5062

You ask the wrong question. HttpContext.Current.User.Identity is a dependency you should encapsulate before you can unit test your code. If encapsulated (probably behind an Interface) you can replace the abstraction with your test data / object.

Upvotes: 3

Related Questions