使用 NUnit 测试方法时,如何解决 WCF 服务方法中 WebOperationContext 为 null 的问题
我有一个使用 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。
最佳答案
通常您会希望以某种方式模拟 WebOperationContext
。 WCFMock 内置了一些东西可以为您做到这一点。
或者,您可以使用一些依赖项注入(inject)从其他地方获取 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;
}
}
当然还有其他方法来设置依赖项注入(inject)方案,在本例中我只是将其传递到服务构造函数中作为示例。
关于wcf - 使用 Nunit 测试 WCF 方法,但 WebOperationContext 为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8804897/