In my last post I showed how to decouple the service consumer from the service proxy using the ServiceLocator pattern.
In order to mock the WCF service, it is necessary to create the following ServiceClientStub:
public class ServiceClientStub<TServiceInterface> : IServiceClient<TServiceInterface>
where TServiceInterface : class
{
private TServiceInterface serviceMock;
public ServiceClientStub(TServiceInterface serviceMock)
{
this.serviceMock = serviceMock;
}
public TServiceInterface Service
{
get { return serviceMock; }
}
public void Dispose() { }
}
This allows you to test the service consumer without the service implementation (using Moq):
var result = ...
var mock = new Mock<IServiceA>();
mock.Setup(s => s.Operation()).Returns(result);
ServiceLocator.Register<IServiceClient<IServiceA>>(
() => new ServiceClientStub<IServiceA>(mock.Object));