Testing WCF methods with Nunit, but WebOperationContext is null

How do you bypass a WebOperationContext object equal to null in a WCF service method when testing a method using NUnit

I have a unit test project using NUnit to verify the data returned by the 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, during the test I get an error

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

relative to WebOperationContext in the SampleService method.

+6
source share
1 answer

Typically, you would like to make fun of WebOperationContext some way. There are several things built into WCFMock that can do this for you.

Alternatively, you can use some dependency injection to get the WebOperationContext from another location, breaking this dependency, for example:

 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 customize the dependency injection scheme, I just used it as a constructor in this case as an example.

+5
source

Source: https://habr.com/ru/post/905628/


All Articles