Max*_*der 6 wcf nunit weboperationcontext
在使用NUnit测试方法时,如何绕过WCF服务方法中的WebOperationContext为空
我有一个单元测试项目使用NUnit来测试WCF方法返回的数据:
public class SampleService
{
public XmlDocument Init ()
{
WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
return _defaultInitializationXMLfile;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我有一个测试方法如下
[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.");
}
}
Run Code Online (Sandbox Code Playgroud)
但是我在测试期间收到错误
SampleServiceUnitTest.DefaultInitializationUnitTest:
System.NullReferenceException : Object reference not set to an instance of an object.
Run Code Online (Sandbox Code Playgroud)
关于SampleService方法中的WebOperationContext.
通常你会想以WebOperationContext某种方式嘲笑它.WCFMock中内置了一些可以为您完成此任务的内容.
或者,您可以使用一些依赖注入从其他地方获取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;
}
}
Run Code Online (Sandbox Code Playgroud)
当然还有其他方法来设置依赖注入方案,我在这种情况下只是将其传递给服务构造函数作为示例.
| 归档时间: |
|
| 查看次数: |
2243 次 |
| 最近记录: |