Are there any ways to mock a WCF client proxy using Rhino mocks framework so I have access to the Channel property? I am trying to unit test Proxy.Close() method but as the proxy is constructed using the abstract base class ClientBase<T>
which has the ICommunicationObject
interface, my unit test is failing as the internal infrastructure of the class is absent in the mock object. Any good ways with code samples would be greatly appreciated.
What you could do is create an interface that inherits from the original service interface and ICommunicationObject
. You could then bind to and mock that interface and still have all the important methods.
For example:
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With