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

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

问题描述:

如何测试利用由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(); 
    } 
} 

我想创建一个从您的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。

根据我的经验,测试类似这种东西所需的时间并不值得。正确完成你的适配器应该主要是做一个传递,因为它的主要目的是为调用代码提供一个测试接缝。在那一点上,它有点像属性和视图。你不需要测试它们,因为你可以直观地检查代码,它非常简单,你知道它是正确的。

这有点晚了,但我只是想办法解决这个问题。由于自动生成的客户端类为局部产生可以这样进行扩展:

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

public partial class LoggingServiceClient : ICloseableLoggingServiceClient 
{ 

} 
现在

LoggingServiceClient团结了从ClientBase<>无论你的服务合同规定,你应该能够嘲笑Close方法与RhinoMocks的ICloseableLoggingServiceClient。所有你需要做的就是确保你正在注入和测试新的接口而不是具体的客户端类。