Search code examples
c#.netunit-testingintegration-testingweboperationcontext

Unit testing with - System.ServiceModel.Web.WebOperationContext - causes a Null exception


I need to ask about that I'm working now on a unit test, and I'm trying to make a test on a specific method within a service.

Inside the method, we have this piece of code

System.ServiceModel.Web.WebOperationContext.Current.IncomingRequest.Headers["KindOfImportantHeader"]; When calling a method I faced a problem with a null exception because the headers are empty.

The issue is that I can't change the implementation of the service and the method; which doesn't allow me to make a (Mock) to pass this issue.

The only change can I perform is just inside the unit test.

So, How can I pass values to headers from the unit test?

Unit Test Framework: XUnit

Unit Test Target Framework: .NET 4.6.1

Service Framework: .NET 4.6.1

Thank You All.


Solution

  • U can create a wrapper around static!

    For example :

    public class IncomingRequstWrapper
      {
          public virtual string KindOfImportantHeader
          {
             get
             {
                return System.ServiceModel.Web.WebOperationContext.Current.IncomingRequest.Headers["KindOfImportantHeader"]
             }
          }
      }
    

    Then you can mock this wrapper.