Sri Harsha Velicheti
Sri Harsha Velicheti

Reputation: 497

Unit testing a object that has dependency on wcf service

I am trying to code an class that has a dependency on a WCF Service, and I would like my class to be unit testable. I came up with the below code, but got into a bit of tricky situation

public class BenefitReason
{
    private IWCFServiceClient _client;

    public  BenefitReason(IWCFServiceClient client)
    {
       _client = client;
    }

    public CanIssueEmercengyBenefit(string benefitReasonCode)
    {
         client.GetEmergencyBenefits().contains(benefitReasonCode);
    }
    //Rest of implementation for Benefit Reason
}

This is unit testable as I can mock IWCFServiceClient, however I lost the control over my client. If the client channel closed between the times the BenefitReason object is created and CanIssueEmercengyBenefit is called then an exception occurs.

Please advice on how to get past this tricky situation of writing code that can be unit-tested vs losing the control on wcf client instantiation.

Upvotes: 0

Views: 329

Answers (2)

Steven
Steven

Reputation: 172826

An addition to TrueWill's answer, you can build a proxy for this:

public WCFServiceClientProxy : IWCFServiceClient
{
    public Benefit[] GetEmergencyBenefits()
    {
        using (var client = new WCFServiceClient())
        {
            return client.GetEmergencyBenefits();
        }
    }
}

By injecting the WCFServiceClientProxy on each call, you prevent any failures and allow to keep the client unaware of the WCF service.

And while you're at it, prevent calling that interface IWCFServiceClient, since it shouldn't concern the client whether it is calling a WCF service or a database.

Upvotes: 3

TrueWill
TrueWill

Reputation: 25543

One option is to instantiate and dispose of the WCF service client in every method call of the interface implementation.

See What is the best workaround for the WCF client `using` block issue? for handling disposal properly.

Upvotes: 1

Related Questions