Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock WCF Web Services with Rhino Mocks

How do I test a class that utilizes proxy clients generated by a Web Service Reference?

I would like to mock the client, but the generated client interface doesn't contain the close method, which is required to properly terminate the proxy. If I don't use the interface, but instead a concrete reference, I get access to the close method but loose the ability to mock the proxy.

I'm trying to test a class similar to this:

public class ServiceAdapter : IServiceAdapter, IDisposable
{
    // ILoggingServiceClient is generated via a Web Service reference
    private readonly ILoggingServiceClient _loggingServiceClient; 

    public ServiceAdapter() : this(new LoggingServiceClient()) {}

    internal ServiceAdapter(ILoggingServiceClient loggingServiceClient)
    {
        _loggingServiceClient = loggingServiceClient;
    }


    public void LogSomething(string msg)
    {
        _loggingServiceClient.LogSomething(msg);
    }

    public void Dispose()
    {
        // this doesn't compile, because ILoggingServiceClient doesn't contain Close(), 
        // yet Close is required to properly terminate the WCF client
        _loggingServiceClient.Close(); 
    }
}
like image 725
Will Avatar asked Apr 15 '10 13:04

Will


1 Answers

I'd create another interface that inherits from your ILoggingServiceClient but adds the Close method. Then create a wrapper class that wraps the LoggingServiceClient instance. Something like:

public interface IDisposableLoggingServiceClient : ILoggingServiceClient
{
    void Close();
}

public class LoggingServiceClientWrapper : IDisposableLoggingServiceClient
{
    private readonly LoggingServiceClient client;

    public LoggingServiceClientWrapper(LoggingServiceClient client)
    {
        this.client = client;
    }

    public void LogSomething(string msg)
    {
        client.LogSomething(msg);
    }

    public void Close()
    {
        client.Close();
    }
}

Now your service adapter can use IDisposableLoggingServiceClient.

like image 200
PatrickSteele Avatar answered Sep 30 '22 15:09

PatrickSteele