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 we
You might consider taking a dependency on System.Web.Abstractions.HttpContextBase instead of using HttpContext.Current. The System.Web.Abstractions assembly has a lot of common ASP.NET Http* classes already wrapped for you. They're used all over the ASP.NET MVC code. If you're using an IoC/DI framework, it's pretty easy to use. For example, in Ninject:
Bind.ToMethod(x => new HttpContextWrapper(HttpContext.Current));
and then in your constructor...
public class SomeWebService
{
private HttpContextBase _httpContext;
public SomeWebService(HttpContextBase httpContext)
{
_httpContext = httpContext;
}
public void SomeOperationNeedingAuthorization()
{
IIdentity userIdentity = _httpContext.User.Identity;
if (!userIdentity.IsAuthenticated)
return;
// Do something here...
}
}
That's WAY oversimplified, but I hope you get the idea... As Aliostad mentioned, you can easily mock HttpContextBase using Rhino Mocks or Moq, etc. to test SomeOperationNeedingAuthorization.