Unit Testing Web Services - HttpContext

后端 未结 5 944
日久生厌
日久生厌 2021-01-31 00:20

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

5条回答
  •  感动是毒
    2021-01-31 00:40

    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.

提交回复
热议问题