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 } 
2
  • possible duplicate of Unit Testing Web Services - HttpContext Commented Jan 13, 2012 at 16:12
  • RE: Attributes, HttpContext.Current isn't compatible with unit testing. You need and abstraction of some type. Commented Jan 13, 2012 at 16:30

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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: stackoverflow.com/questions/5251636/…
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.