c# - 单元测试服务和模拟自动生成的 WCF 客户端代理

标签 c# web-services unit-testing wcf mocking

我在服务中引用自动生成的 WCF 客户端。

//Autogenerated Service client
public partial class ServiceClient : 
    System.ServiceModel.ClientBase<IService>, IService 
{
    //...
}
//Autogenerated Interface Client
public interface IService {
    //...
}

通过以下方式:

public MyService{

    public IExternalWsClientFactory ExternalWsClientFactory {get; set; }

    public void MyMethod(){
        using (var wsCliente = ExternalWsClientFactory.ServiceClient())
        { 
            //... 
        }
    }
}

public class ExternalWsClientFactory : IExternalWsClientFactory
{
    public ServiceClient ServiceClient()
    {
        var wsClient = new ServiceClient();
        return wsClient;
    }
}

我引用该实现是因为我想使用using 语句 在代码块的末尾处理资源。并且因为 IDisposableClientBase 下并且接口(interface)不是局部的。

我的问题是我想模拟 ServiceClient(我已经模拟了 External WsClientFactory)但是因为我使用了实现,所以我很难做到这个。

注意:实现中自动生成的方法ServiceClient不是virtual

最佳答案

该类是部分的。界面不是。

创建您自己的派生自原始接口(interface)的接口(interface),并使用 IDisposable 对其进行扩展。

public interface IServiceClient: ICommunicationObject, IService, IDisposable { }

使用自定义接口(interface)扩展分部类

public partial class ServiceClient : IServiceClient { }

现在您应该可以通过 using 语句使用您的扩展接口(interface)

public class ExternalWsClientFactory : IExternalWsClientFactory {
    public IServiceClient ServiceClient() {
        var wsClient = new ServiceClient();
        return wsClient;
    }
}

关于c# - 单元测试服务和模拟自动生成的 WCF 客户端代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41962863/

相关文章:

c# - 为什么接口(interface)不能指定静态方法?

c# - 反射使HashCode不稳定

python - 在 Python 中模拟 assert_called_with

java - Junit,测试,Flyway : Can you combine @Before and @Flyway annotations?

c# - SQL 添加字符串作为参数

c# - 以编程方式在 Excel 中插入单元格注释

java - 如何在 ReSTLet 中发送错误响应?

c# - 'System.ServiceModel.Diagnostics.TraceUtility' 的类型初始值设定项

c# - ...可能不会在这种情况下使用...而序列化

javascript - "clock"指令的 Angular 单元测试 $interval