一千萬個為什麽

搜索

如何使用Rhino Mocks模擬WCF Web服務

如何測試使用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(); 
    }
}

最佳答案

我創建了另一個繼承自ILoggingServiceClient的接口,但添加了C​​lose方法。然後創建一個包裝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();
    }
}

現在您的服務適配器可以使用IDisposableLoggingServiceClient。

轉載註明原文: 如何使用Rhino Mocks模擬WCF Web服務