10
有沒有什麼方法可以模仿使用Rhino mocks框架的WCF客戶端代理,因此我可以訪問Channel屬性?我試圖單元測試Proxy.Close()方法,但由於代理是使用具有ICommunicationObject
接口的抽象基類ClientBase<T>
構造的,所以我的單元測試失敗,因爲類的內部基礎結構在模擬對象中不存在。任何代碼示例的好方法將不勝感激。模擬WCF客戶端代理的最佳方法
有沒有什麼方法可以模仿使用Rhino mocks框架的WCF客戶端代理,因此我可以訪問Channel屬性?我試圖單元測試Proxy.Close()方法,但由於代理是使用具有ICommunicationObject
接口的抽象基類ClientBase<T>
構造的,所以我的單元測試失敗,因爲類的內部基礎結構在模擬對象中不存在。任何代碼示例的好方法將不勝感激。模擬WCF客戶端代理的最佳方法
您可以做的是創建一個繼承原始服務接口和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();
看到一篇文章[託管-模擬作爲-WCF服務(http://bronumski.blogspot.com.au/2011/09/hosting-mock-as- wcf-service.html)和相關答案http://stackoverflow.com/a/10306934/52277 – 2013-08-27 13:04:11