简体   繁体   中英

Unit test Service and Mock Autogenerated WCF Client proxy

I'm referencing an Auto-generated WCF Client in a Service.

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

In the following manner:

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;
    }
}

I reference the implementation because I want to use the using statement to dispose resources at the end of the code block. And because the IDisposable is under ClientBase and the interface is not partial.

My problem is that I want to mock ServiceClient (I already mock External WsClientFactory ) but since I use the implementation I'm having hard trouble to do this.

NOTE: the auto-generated method ServiceClient in the implementation is not virtual .

The class is partial. The interface is not.

Create your own interface that derives from the original interface and extends it with IDisposable .

public interface IServiceClient: ICommunicationObject, IService, IDisposable { }

extend the partial class with your custom interface

public partial class ServiceClient : IServiceClient { }

and now you should be able to use your extended interface with using statement

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM