6

使用 NUnit 测试方法时,如何解决 WCF 服务方法中 WebOperationContext 为空的问题

我有一个单元测试项目,使用 NUnit 来测试 WCF 方法返回的数据:

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

然后我有一个测试方法如下

[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.");
   }
 }

但是我在测试期间遇到错误

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

关于 SampleService 方法中的 WebOperationContext。

4

1 回答 1

5

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.

于 2012-01-10T14:42:20.880 回答