如何使用Rhino Mocks模拟WCF Web服务

Wil*_*ill 6 unit-testing web-services rhino-mocks

如何测试使用Web服务引用生成的代理客户端的类?

我想模拟客户端,但生成的客户端接口不包含正确终止代理所需的close方法.如果我不使用接口,而是使用具体的引用,我可以访问close方法,但却无法模拟代理.

我正在尝试测试类似这样的类:

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(); 
    }
}
Run Code Online (Sandbox Code Playgroud)

Pat*_*ele 1

我将创建另一个继承自 ILoggingServiceClient 的接口,但添加 Close 方法。然后创建一个包装 LoggingServiceClient 实例的包装类。就像是:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

现在您的服务适配器可以使用 IDisposableLoggingServiceClient。