Testing WCF methods with Nunit but WebOperationContext is null

2.5k views Asked by At

How do you get around the WebOperationContext being null in a WCF service method when testing the method using NUnit

I have a unit test project using NUnit to test data returned by a WCF Method:

public class SampleService
{
   public XmlDocument Init ()
   {
      WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
      return _defaultInitializationXMLfile;
   }
}

Then I have a Test Method as follows

[TextFixture]
public class SampleServiceUnitTest
{
   [Test]
   public void DefaultInitializationUnitTest
   {
      SampleService sampleService = new SampleService();
      XMLDocument xmlDoc = sampleService.Init();
      XMLNode xmlNode = xmlDoc.SelectSingleNode("defaultNode");
      Assert.IsNotNull(xmlNode, "the default XML element does not exist.");
   }
 }

However I'm getting an error during the test stating

 SampleServiceUnitTest.DefaultInitializationUnitTest:
 System.NullReferenceException : Object reference not set to an instance of an object.

regarding the WebOperationContext in the SampleService Method.

1

There are 1 answers

0
CodingWithSpike On

Typically you would want to mock the WebOperationContext in some way. There is some stuff built into WCFMock that can do this for you.

Alternatively, you can use some dependency injection to get the WebOperationContext from somewhere else, breaking that dependency, like:

public class SampleService
{
   private IWebContextResolver _webContext;

   // constructor gets its dependency, a web context resolver, passed to it.
   public SampleService(IWebContextResolver webContext)
   {
      _webContext = webContext;
   }

   public XmlDocument Init ()
   {
      _webContext.GetCurrent().OutgoingResponse.ContentType = "text/xml";
      return _defaultInitializationXMLfile;
   }
}

public class MockWebContextResolver : IWebContextResolver
{
    public WebOperationContext GetCurrent()
    {
        return new WebOperationContext(...); // make and return some context here
    }
}

public class ProductionWebContextResolver : IWebContextResolver
{
    public WebOperationContext GetCurrent()
    {
        return WebOperationContext.Current;
    }
}

There are of course other ways to set up a dependency injection scheme, I just used passing it into the service constructor in this case as an example.