Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock WCF client using Moq?

In my project I am using: SL5+ MVVM+ Prism + WCF + Rx + Moq + Silverlight Unit Testing Framework.

I am new to unit-testing and have recently started into DI, Patterns (MVVM) etc. Hence the following code has a lot of scope for improvement (please fell free to reject the whole approach I am taking if you think so).

To access my WCF services, I have created a factory class like below (again, it can be flawed, but please have a look):

namespace SomeSolution
{
    public class ServiceClientFactory:IServiceClientFactory
    {
        public CourseServiceClient GetCourseServiceClient()
        {
            var client = new CourseServiceClient();
            client.ChannelFactory.Faulted += (s, e) => client.Abort();
            if(client.State== CommunicationState.Closed){client.InnerChannel.Open();}
            return client;
        }

        public ConfigServiceClient GetConfigServiceClient()
        {
            var client = new ConfigServiceClient();
            client.ChannelFactory.Faulted += (s, e) => client.Abort();
            if (client.State == CommunicationState.Closed) { client.InnerChannel.Open(); }
            return client;
        }

        public ContactServiceClient GetContactServiceClient()
        {
            var client = new ContactServiceClient();
            client.ChannelFactory.Faulted += (s, e) => client.Abort();
            if (client.State == CommunicationState.Closed) { client.InnerChannel.Open(); }
            return client;
        }
    }
}

It implements a simple interface as below:

public interface IServiceClientFactory
{
    CourseServiceClient GetCourseServiceClient();
    ConfigServiceClient GetConfigServiceClient();
    ContactServiceClient GetContactServiceClient();
}

In my VMs I am doing DI of the above class and using Rx to call WCF as below:

var client = _serviceClientFactory.GetContactServiceClient();
try
{

    IObservable<IEvent<GetContactByIdCompletedEventArgs>> observable =
        Observable.FromEvent<GetContactByIdCompletedEventArgs>(client, "GetContactByIdCompleted").Take(1);

    observable.Subscribe(
        e =>
            {
                if (e.EventArgs.Error == null)
                {                                    
                    //some code here that needs to be unit-tested

                }
            },
        ex =>
        {
            _errorLogger.ProcessError(GetType().Name, MethodBase.GetCurrentMethod().Name, ErrorSource.Observable, "", -1, ex);
        }
        );
    client.GetContactByIdAsync(contactid, UserInformation.SecurityToken);
}
catch (Exception ex)
{
    _errorLogger.ProcessError(GetType().Name, MethodBase.GetCurrentMethod().Name, ErrorSource.Code, "", -1, ex);
}

Now I want to build unit tests (yes, its not TDD). But I don't understand where to start. With Moq I can't mock the BlahServiceClient. Also no svcutil generated interface can help because async methods are not part of the auto-generated IBlahService interface. I may prefer to extend (through partial classes etc) any of the auto generated classes, but I would hate to opt for manually building all the code that svcutil can generate (frankly considering time and budget).

Can someone please help? Any pointer in the right direction would help me a lot.

like image 739
Dharmesh Avatar asked Jan 14 '23 15:01

Dharmesh


1 Answers

When mocking your service client you are actually mocking one of the interfaces it implements. So in your case it may be IContactService.

The generated code implements both System.ServiceModel.ClientBase<IContactService> and IContactService. Your dependency provider (in your case a factory) is returning ContactServiceClient - change this to IContactService for starters. This will aid your DI now and in the future.

Ok, you're already have an abstract factory and now they return your service interface IContactService. You're using interfaces only now so the mocking is quite trivial.

First some assumptions about the code you're trying to exercise. The code snippet provided messages both the abstract factory and the service client. Provided that the //some code here that needs to be unit-tested section is not going to interact with any other dependencies then you're looking to mock out both the factory and the service client so that you test is isolated to just the method body code.

I've made an adjustment for the sake of example. Your interfaces:

public class Contact {
    public string Name { get; set; }
}

public interface IContactService {
    Contact GetContactById(int contactid);
}

public interface IContactServiceFactory {
    IContactService GetContactService();
}

Then your test would look summing like this:

public void WhateverIsToBeTested_ActuallyDoesWhatItMustDo() {

    // Arrange
    var mockContactService = new Mock<IContactService>();
    mockContactService.Setup(cs => cs.GetContactById(It.IsAny<int>()))
        .Returns(new Contact { Name = "Frank Borland" });

    var fakeFactory = new Mock<IContactServiceFactory>();
    fakeFactory.Setup(f => f.GetContactService())
        .Returns(mockContactService.Object);

    /* i'm assuming here that you're injecting the dependency intoto your factory via the contructor - but 
     * assumptions had to be made as not all the code was provided
     */
    var yourObjectUnderTest = new MysteryClass(fakeFactory.Object);

    // Act
    yourObjectUnderTest.yourMysteryMethod();

    // Assert
    /* something mysterious, but expected, happened */            

}

EDIT: Mocking the Async Methods

The async generated methods are not part of your service methods and is created by WCF as part of the Client class. To mock those as an Interface do the following:

  1. Extract the Interface of the ContactServiceClient class. In VS it's simply a right-click (on the class name), refactor, extract interface. And choose only the applicable methods.

  2. The ContactServiceClient class is partial so create a new class file and redefine the ContactServiceClient class to implement the new IContactServiceClient interface you just extracted.

    public partial class ContactServiceClient : IContactServiceClient {
    }
    

Like such and now the client class ALSO implements the new interface with the selected async methods. When refreshing your service interface and the service class is re-generated - you don't have to re-extract the interface as you've created a separate partial class with the interface reference.

  1. Create a new factory to return the new interface

    public interface IContactServiceClientFactory {
        IContactServiceClient GetContactServiceClient();
    }
    
  2. Modify the test to work with that interface.

like image 195
Quinton Bernhardt Avatar answered Jan 22 '23 22:01

Quinton Bernhardt