Unit testing WCF async calls using Rx
-
Wednesday, December 26, 2012 6:28 AM
My project uses the following:
Silverlight 5 + prism + WCF services + MOQ + Silverlight Unit Testing Framework
Also, I am new to Rx framework and unit testing both, so please feel free to reject my whole approach (as explained below).
To access my WCF services, I have created a factory class that gives me back instance of the WCF Service-Client like below:
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; } } }
The following is the interface that the above class is implementing:
public interface IServiceClientFactory { CourseServiceClient GetCourseServiceClient(); ConfigServiceClient GetConfigServiceClient(); }
In my ViewModels I am utilizing the above class and calling WCF through Rx like below (needless to say I am doing DI of ServiceClientFactory in my VM):
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, how do I build Unit-tests (and also integration test) for the above code? More specifically, how do I mock my WCF service client (considering that Async definitions are not part of IService)? Am I doing any mistake in creating serviceclientfactory class above? With my little investigation, I found people do things like extending partial wcf client class definitions etc (which I would prefer not to do, considering I don't want to fiddle with svcutil generated code).
I would be greatly thankful if someone can suggest some code.
Thanks in advance,
Dharmesh
- Edited by Dharmesh1 Wednesday, December 26, 2012 7:18 AM

