I want to write unit tests for a web service. I create my test project, reference my web project (not service reference, assembly reference), then write some code to test the web services – they work fine. However, there are some services which make sure the user is logged in to the web application by using HttpContext.Current.User.Identity.IsAuthenticated.
In the context of the tests, there is no such thing as HttpContext, so the tests always fail. How should these kinds of web services be unit tested?
Here is a related discussion.
I stopped referencing
HttpContext.Currentdirectly. and use this class instead:and use
HttpContextFactory.Currentinstead ofHttpContext.Currentin our code.Then you write this in your test:
where GetMockedHttpContext() is from here and looks like this:
It uses a mocking framework called moq
In your test project you have to add a reference to
System.WebandSystem.Web.Abstractions, whereHttpContextBaseis defined.