2010-04-15 88 views
6

如何測試利用由Web服務引用生成的代理客戶端的類?如何使用Rhino Mocks模擬WCF 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(); 
    } 
} 

回答

1

我想創建一個從您的ILoggingServiceClient繼承,但增加了關閉方法的另一個接口。然後創建一個包裝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。

0

根據我的經驗,測試類似這種東西所需的時間並不值得。正確完成你的適配器應該主要是做一個傳遞,因爲它的主要目的是爲調用代碼提供一個測試接縫。在那一點上,它有點像屬性和視圖。你不需要測試它們,因爲你可以直觀地檢查代碼,它非常簡單,你知道它是正確的。

0

這有點晚了,但我只是想辦法解決這個問題。由於自動生成的客戶端類爲局部產生可以這樣進行擴展:

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

public partial class LoggingServiceClient : ICloseableLoggingServiceClient 
{ 

} 
現在

LoggingServiceClient團結了從ClientBase<>無論你的服務合同規定,你應該能夠嘲笑Close方法與RhinoMocks的ICloseableLoggingServiceClient。所有你需要做的就是確保你正在注入和測試新的接口而不是具體的客戶端類。