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.
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:
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.