3

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
}
Josh
  • 8,219
  • 13
  • 76
  • 123
  • possible duplicate of [Unit Testing Web Services - HttpContext](http://stackoverflow.com/questions/4028056/unit-testing-web-services-httpcontext) – BNL Jan 13 '12 at 16:12
  • RE: Attributes, HttpContext.Current isn't compatible with unit testing. You need and abstraction of some type. – BNL Jan 13 '12 at 16:30

2 Answers2

3

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.

Dirk Brockhaus
  • 4,922
  • 3
  • 38
  • 47
  • 1
    It’s harder to find an entry link on that theme as I thought. If you google for Dependency Injection + HttpContext you get much stuff, but most of it is related to special dependency injection containers. Here is a link with poor man’s dependency injection giving you the general idea: http://stackoverflow.com/questions/5251636/asp-net-mvc-and-ioc-chaining-injection – Dirk Brockhaus Jan 13 '12 at 22:04
1

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.

Red Taz
  • 4,159
  • 4
  • 38
  • 60