【问题标题】:Testing WCF methods with Nunit but WebOperationContext is null使用 Nunit 测试 WCF 方法,但 WebOperationContext 为空
【发布时间】:2012-02-06 23:03:03
【问题描述】:

在使用 NUnit 测试方法时,如何避免 WebOperationContext 在 WCF 服务方法中为空

我有一个单元测试项目,使用 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。

【问题讨论】:

    标签: wcf nunit weboperationcontext


    【解决方案1】:

    通常你会想以某种方式模拟WebOperationContextWCFMock 中内置了一些东西可以为你做这件事。

    或者,您可以使用一些依赖注入从其他地方获取 WebOperationContext,从而打破这种依赖关系,例如:

    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;
        }
    }
    

    当然还有其他方式来设置依赖注入方案,我这里只是以传递给服务构造函数为例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多