最佳的模拟WCF客户端代理的方法

10

有没有方法可以使用Rhino mocks框架来模拟WCF客户端代理,以便我可以访问Channel属性?我正在尝试对Proxy.Close()方法进行单元测试,但是由于代理是使用抽象基类ClientBase<T>构造的,该基类具有ICommunicationObject接口,因此我的单元测试失败了,因为模拟对象中缺少了类的内部基础结构。非常感谢任何带有代码示例的好方法。


请查看一篇名为“将模拟服务作为WCF服务托管”的文章(http://bronumski.blogspot.com.au/2011/09/hosting-mock-as-wcf-service.html)以及相关答案(https://dev59.com/l2HVa4cB1Zd3GeqPkjra#10306934)。 - Michael Freidgeim
1个回答

21

您可以创建一个继承自原始服务接口和 ICommunicationObject 的接口。然后,您可以绑定并模拟该接口,仍然具有所有重要的方法。

例如:

public interface IMyProxy : IMyService, ICommunicationObject
{
   // Note that IMyProxy doesn't implement IDisposable. This is because
   // you should almost never actually put a proxy in a using block, 
   // since there are many cases where the proxy can throw in the Dispose() 
   // method, which could swallow exceptions if Dispose() is called in the 
   // context of an exception bubbling up. 
   // This is a general "bug" in WCF that drives me crazy sometimes.
}

public class MyProxy : ClientBase<IMyService>, IMyProxy
{
   // proxy code 

}

public class MyProxyFactory
{
   public virtual IMyProxy CreateProxy()
   {
      // build a proxy, return it cast as an IMyProxy.
      // I'm ignoring all of ClientBase's constructors here
      // to demonstrate how you should return the proxy 
      // after it's created. Your code here will vary according 
      // to your software structure and needs.

      // also note that CreateProxy() is virtual. This is so that 
      // MyProxyFactory can be mocked and the mock can override 
      // CreateProxy. Alternatively, extract an IMyProxyFactory
      // interface and mock that. 
      return new MyProxy(); 
   } 
} 

public class MyClass
{
   public MyProxyFactory ProxyFactory {get;set;}
   public void CallProxy()
   {
       IMyProxy proxy = ProxyFactory.CreateProxy();
       proxy.MyServiceCall();
       proxy.Close();
   }
}


// in your tests; been a while since I used Rhino  
// (I use moq now) but IIRC...:
var mocks = new MockRepository();
var proxyMock = mocks.DynamicMock<IMyProxy>();
var factoryMock = mocks.DynamicMock<MyProxyFactory>();
Expect.Call(factoryMock.CreateProxy).Return(proxyMock.Instance);
Expect.Call(proxyMock.MyServiceCall());
mocks.ReplayAll();

var testClass = new MyClass();
testClass.ProxyFactory = factoryMock.Instance;
testClass.CallProxy();

mocks.VerifyAll();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接