Unit Testable WCF Web Services in MVVM and Silverlight 4

Unit Testable WCF Web Services in MVVM and Silverlight 4

In all my previous MVVM in Silverlight 4 posts i was avoiding to address one painful aspect of the Silverlight: calling WCF Web Services.

And it was not without reason. Lets face it, consuming WCF Web Services from your Silverlight application can be pretty hard.

I mean hard to do it in a clean way off course.

Yes we all know how to create a Silverlight enabled WCF Web Service from Visual Studio but things become messy from that point.

First question is how to invoke methods of the web service?

Should we use Add Web Service Reference from the Visual Studio and and get the service proxy generated for us by the IDE?

If you go down that route, its easy to start and you will be invoking web service methods asynchronously in no time, but you will pay the price for that simplicity later, that is for sure.

Next problem is how to Unit Test those web service calls – its impossible to abstract the generated proxy in a clean way.

Then if you change your Web Service signature, you have to rebuild your Proxy. This can be troublesome especially if more than one person is working on the same project (can be avoided using build scripts to rebuild proxy automatically during compilation but still i don’t like that).

Also invoking web service methods asynchronously is tedious work in terms of writing the same code over and over again.

You have to subscribe to the OnCompleted event, and then invoke the actual asynchronous method, and then when your OnComplete handler is invoked, you can process the results of the web service method.

Not to mention the lifetime of the generated proxy, and handling exceptions that could be thrown in the service etc.

So as we see Visual Studio (or command line) proxy generating helps us in many ways but also brings new problems that are hard to solve.

I figured that there has to be a better way to solve this everyday problem so while working on my personal MVVM framework (yes, everyone is building one these days) i was setting these goals regarding the Web Service calls from my MVVM applications:

  1. simplify as much as possible asynchronous invocation of Web Service methods (avoid writing boring boilerplate code for each call)
  2. get rid of the Add Service Reference approach completely if possible
  3. make the Web Services unit testable (hide them behind some interface so we can mock them in our unit tests)
  4. simplify exception handling
  5. fault tolerance (if web service client is faulted by exception it should be automatically recreated)

If this list of features looks interesting to you then you will soon see that all this is possible in a simple way by using ChannelFactory<T> and creating the Web Service client channel for the web service manually.

So lets start: In our example we will be using a fake WeatherForecast web service that will have just one method GetForecast and it will accept DateTime as parameter and return a simple class DailyForecast as a result that will have some fake data just to have something to work with.

First of all we need to create a service contract interface for WeatherForecastWebService and since we must allow the Silverlight client to call this web service asynchronously we will add conditional compilation code regions in the interface with additional asynchronous signatures for the GetForecast method (BeginGetForecast and EndGetForecast) like this:

01namespace Abstractions
02{
03    [ServiceContract]
04    public interface IWeatherForecastService
05    {
06 
07#if SILVERLIGHT
08        [OperationContract(AsyncPattern=true)]
09        IAsyncResult BeginGetForecast(DateTime day, AsyncCallback callback, object state);
10        DailyForecast EndGetForecast(IAsyncResult result);
11#else
12 
13        [OperationContract]
14        DailyForecast GetForecast(DateTime day);
15#endif
16    }
17}

and here is the DailyForecast Data Transfer Object (DTO) class that we will receive from the web service:

01namespace Abstractions
02{
03    [DataContract]
04    public class DailyForecast
05    {
06        [DataMember]
07        public DateTime Date { get; set; }
08 
09        [DataMember]
10        public string Description { get; set; }
11    }
12}

Note the DataContract and DataMember attributes, they must be provided in order to receive the class on the client properly.

Since we are to consume the web service on the Silverlight client we must make available all the classes to the client side.

Here is how we are going to accomplish this: We must define service contract interface and all the classes that the service will return both on server and on the Silverlight client. We will do that by creating a Abstractions.Web class library project that will hold the service contract interface IWeatherForecastService all the needed Data Transfer Object classes (in this example its just DailyForecast class), and then we will also create Abstractions.Silverlight – Silverlight class library project where we will add the same classes (DTO’s and service contract interface) as links – by going to to right click menu on the project and choose Add -> Existing Item and add all needed files and click on Add As Link button instead of Add button.

here is how this setup looks in my Visual Studio instance: So now that we have same set of shared classes on client and on the server we can proceed with creating a web service helper class that will allow us to invoke asynchronous methods in a simple way without having to do lot of boilerplate code. As we said we want to be able to mock that helper in our Unit Tests we need to have an interface for it so lets define that first:

01namespace Framework.Abstractions.Silverlight.WebServices
02{
03    public interface IWebServiceClientFactory<TWebService> :  IDisposable
04    {
05        TWebService WebServiceInstance
06        {
07            get;
08        }
09 
10        void Invoke<TParam, TResult>(TParam param, object state,
11                                     Func<TParam, AsyncCallback, object, IAsyncResult> beginOp,
12                                     Func<IAsyncResult, TResult> endOp,
13                                     Action<AsyncWebServiceCallResult<TResult>> onComplete);
14 
15    }
16}

As you can see we are defining the WebServiceClientFactory of TWebService that will expose a web service client instance WebServiceInstance if we want to call it directly but more important will be the generic Invoke method for generic asynchronous calls that will allow to call any method on any web service in a simple way just by specifying the parameter, then the begin and end method we want to calla and a method that should be called with the received results when web service call is finished.

Our helper class will also implement IDisposable so we can cleanup properly.

Let us investigate the Invoke method. From its signature we see that it is a generic function and that it has two type parameters, TParam that is the type of the parameter sent to our web service when we invoke the web method, and TResult that is the type of the result we expect from the method.

Then there is a object state that we want to send to the web service method (we can pass NULL there if we don’t need it).

And then comes the fun part: Parameter beginOp is a BEGIN* method that will be invoked, and parameter endOp is the END* method that will be invoked for the web service call. In our case we will supply here BeginGetForecast and EndGetForecast methods using the WebServiceInstance property of the same factory class. But its important to note here that if our web service would have other methods that support asynchronous invoking with these BEGIN* and END* signatures, we could call them in same way, just passing another pair of Begin* and End* methods.

Last parameters is an Action> that will be called when the web method call is finished. This action will receive the instance of custom generic class AsyncWebServiceCallResult whose type parameter is the DailyForecast – result we would normally expect from the web method. So here is the definition of generic AsyncWebServiceCallResult class:

1namespace Framework.Abstractions.Silverlight.WebServices
2{
3    public class AsyncWebServiceCallResult<TResult>
4    {
5        public TResult Result { get; set; }
6        public bool WasSuccessfull { get; set;}
7        public Exception Exception { get; set; }
8    }
9}

So this class is just a wrapper around the TResult we would usually receive from the web service method call and it adds just two more properties: boolean WasSuccessfull and Exception. If web method call is executed without problems WasSuccessfull is set to true and Exception is null, and on the other hand if there is some exception thrown during the invocation of the web service method call Exception will hold the Exception thrown and WasSuccessfull will be set to false.

So lets see how we would use this Web Service factory to call our WeatherForecastService:

1var weatherServiceFactory = SimpleServiceLocator.Instance.Retrieve<IWebServiceClientFactory<IWeatherForecastService>>();
2weatherServiceFactory.Invoke(date, null,
3                                          weatherServiceFactory.WebServiceInstance.BeginGetForecast,
4                                          weatherServiceFactory.WebServiceInstance.EndGetForecast,
5                                          this.OnResultReceived);

And the method that will be called when results is received would look like this:

01private void OnResultReceived(AsyncWebServiceCallResult<DailyForecast> asyncResult)
02{
03    if (asyncResult.WasSuccessfull)
04    {
05        this.StatusMessage = "New forecast received ok.";
06        this.ForecastThatWasReceived = asyncResult.Result;
07 
08    }
09    else
10    {
11        this.ForecastThatWasReceived = null;
12        this.StatusMessage = "Error result received: Error description: " + asyncResult.Exception.Message;
13    }
14}

And you can use this generic helper class to create wrapper around ANY web service exposed to your Silverlight application.

You just instantiate this class giving it the contract interface of the desired web service and URL of the web service.

WebServiceClientFactory will do all the plumbing for you and create ChannelFactory and web service client and expose it in WebServiceInstance property.

Then you can use Invoke method of the class to call ANY web service method with single line of code (you need on complete action to receive the result but you cannot avoid that – its asynchronous call after all).

Usable?  🙂

So now that you have seen how we would use the interface of our web service factory, lets see how its really implemented:

001using System;
002using System.Collections.Generic;
003using System.Diagnostics;
004using System.ServiceModel;
005using System.ServiceModel.Channels;
006using System.Windows;
007using Framework.Abstractions.Silverlight.WebServices;
008using System.Linq.Expressions;
009 
010namespace Framework.Implementors.Silverlight.WebServices
011{
012    public class WebServiceClientFactory<TWebService> : IWebServiceClientFactory<TWebService> where  TWebService : class
013    {
014        private CustomBinding binding;
015        private readonly string endpointAddress;
016        private ChannelFactory<TWebService> channelFactory;
017 
018        public WebServiceClientFactory(CustomBinding binding, string endpointAddress)
019        {
020            this.binding = binding;
021            this.endpointAddress = endpointAddress;
022        }
023 
024        public WebServiceClientFactory(string endpointAddress)
025        {
026            this.endpointAddress = endpointAddress;
027        }
028 
029        public TWebService WebServiceInstance
030        {
031            get
032            {
033                if (this.channelFactory == null || this.channel == null)
034                {
035                    this.InitializeWeatherServiceClient();
036                }
037 
038                return this.channel;
039            }
040 
041            private set
042            {
043                this.channel = value;
044            }
045        }
046        private TWebService channel;
047 
048        private void InitializeWeatherServiceClient()
049        {
050            Debug.WriteLine("Initializing factory and channel in " + this.GetType().Name);
051            if (this.binding == null)
052            {
053                var elements = new List<BindingElement>();
054                elements.Add(new BinaryMessageEncodingBindingElement());
055                elements.Add(new HttpTransportBindingElement());
056                this.binding = new CustomBinding(elements);
057            }
058 
059            channelFactory = new ChannelFactory<TWebService>(this.binding, new EndpointAddress(endpointAddress));
060            channel = this.GetNewChannelFromCurrentFactory();
061        }
062 
063        public void Invoke<TParam, TResult>(TParam param, object state, Func<TParam, AsyncCallback, object, IAsyncResult> beginOp, Func<IAsyncResult, TResult> endOp, Action<AsyncWebServiceCallResult<TResult>> onComplete)
064        {
065            beginOp(param, (ar) =>
066                {
067                    var asyncResult = new AsyncWebServiceCallResult<TResult>();
068                    try
069                    {
070                        asyncResult.Result = endOp(ar);
071                        asyncResult.WasSuccessfull = true;
072                    }
073                    catch (Exception e)
074                    {
075                        asyncResult.WasSuccessfull = false;
076                        asyncResult.Exception = e;
077                    }
078 
079                    if (Deployment.Current.Dispatcher.CheckAccess())
080                    {
081                        onComplete(asyncResult);
082                    }
083                    else
084                    {
085                        Deployment.Current.Dispatcher.BeginInvoke(() => onComplete(asyncResult));
086                    }
087 
088                }, state );
089        }
090 
091        private TWebService GetNewChannelFromCurrentFactory()
092        {
093 
094            var newChannel = channelFactory.CreateChannel();
095 
096            var channelAsCommunicationObject = (newChannel as ICommunicationObject);
097            if (channelAsCommunicationObject != null)
098            {
099                channelAsCommunicationObject.Faulted += ChannelFaulted;
100            }
101 
102            return newChannel;
103        }
104 
105        void ChannelFaulted(object sender, EventArgs e)
106        {
107            Debug.WriteLine("Service channel faulted in " + this.GetType().Name);
108            var communicationObject = (this.channel as ICommunicationObject);
109            if (communicationObject != null)
110            {
111                communicationObject.Abort();
112 
113                this.channel = this.GetNewChannelFromCurrentFactory();
114            }
115        }
116 
117        ~WebServiceClientFactory()
118        {
119            Dispose(false);
120        }
121 
122        public void Dispose()
123        {
124            Dispose(true);
125        }
126 
127        protected void Dispose(bool disposing)
128        {
129            if (disposing)
130            {
131                // dispose managed stuff
132                Debug.WriteLine("Disposing managed resources in " + this.GetType().Name);
133                var communicationObject = (this.channel as ICommunicationObject);
134                if (communicationObject != null)
135                {
136                    communicationObject.Faulted -= this.ChannelFaulted;
137 
138                    try
139                    {
140                        communicationObject.Close();
141                    }
142                    catch (Exception)
143                    {
144                        try
145                        {
146                            communicationObject.Abort();
147                        }
148                        catch
149                        {
150                        }
151                    }
152                }
153            }
154 
155            // here we would dispose unmanaged stuff
156        }
157 
158    }
159}

Class has multiple constructors so you can choose how to set it up. The simplest usage is just to specify the string URL of the web service. Here is how i setup my IOC in the bootstrapper of my Silverlight application:

1SimpleServiceLocator.Instance.RegisterAsSingleton<IWebServiceClientFactory<IWeatherForecastService>>
2(new WebServiceClientFactory<IWeatherForecastService>("http://localhost:1000/WeatherForecastService.svc"));

When constucted like this factory class uses standard Binding that would be created for you if you would add the Web Service Reference from visual studio and it will use that Binding and that given URL as endpoint to create a generic ChannelFactory of the web service type provided in type param

<TWebService> and then it will create a communication channel to communicate with web service of given type on the given URL.

Here is the code that is doing this part:

01private void InitializeWeatherServiceClient()
02{
03    Debug.WriteLine("Initializing factory and channel in " + this.GetType().Name);
04    if (this.binding == null)
05    {
06        var elements = new List<BindingElement>();
07        elements.Add(new BinaryMessageEncodingBindingElement());
08        elements.Add(new HttpTransportBindingElement());
09        this.binding = new CustomBinding(elements);
10    }
11 
12    channelFactory = new ChannelFactory<TWebService>(this.binding, new EndpointAddress(endpointAddress));
13    channel = this.GetNewChannelFromCurrentFactory();
14}

There is a another constructor that accepts Binding if you want to provide your own.
Next interesting part of the class is the Invoke method:

01public void Invoke<TParam, TResult>(TParam param, object state, Func<TParam, AsyncCallback, object, IAsyncResult> beginOp, Func<IAsyncResult, TResult> endOp, Action<AsyncWebServiceCallResult<TResult>> onComplete)
02{
03    beginOp(param, (ar) =>
04        {
05            var asyncResult = new AsyncWebServiceCallResult<TResult>();
06            try
07            {
08                asyncResult.Result = endOp(ar);
09                asyncResult.WasSuccessfull = true;
10            }
11            catch (Exception e)
12            {
13                asyncResult.WasSuccessfull = false;
14                asyncResult.Exception = e;
15            }
16 
17            if (Deployment.Current.Dispatcher.CheckAccess())
18            {
19                onComplete(asyncResult);
20            }
21            else
22            {
23                Deployment.Current.Dispatcher.BeginInvoke(() => onComplete(asyncResult));
24            }
25 
26        }, state );
27}

As you can see no big deal there, we just invoke the BEGIN* operation with lambda method as complete handler where we wrap the call to END* operation in Try..Catch so we can recover from any exception.
If there was an exception we set WasSuccessfull to false and Exception property.
If all went ok we populate the Result property with the result of the web method call and then we invoke the onComplete action that was supplied by the user of the class.
But we make sure that we invoke it on the UI thread just as a convenience for the user so he does not need to do it by himself.

One more important thing is that if our web service channel gets faulted by some communication error we will catch that event and recreate the channel:

01void ChannelFaulted(object sender, EventArgs e)
02{
03    Debug.WriteLine("Service channel faulted in " + this.GetType().Name);
04    var communicationObject = (this.channel as ICommunicationObject);
05    if (communicationObject != null)
06    {
07        communicationObject.Abort();
08 
09        this.channel = this.GetNewChannelFromCurrentFactory();
10    }
11}

Previously, we subscribed that method to the OnFaulted event on the channel.

Other parts of the class are not too much interesting so you can dig yourself if you want.

So lets see how we would use the class in our view model.
Here is the listing of the ForecastViewModel that will allow us to invoke the WeatherForecast web service:

01using System;
02using Abstractions;
03using Framework.Abstractions.Silverlight.Intefaces;
04using Framework.Abstractions.Silverlight.WebServices;
05using Framework.Implementors.Silverlight.Comanding;
06using Framework.Implementors.Silverlight.MVVM;
07 
08namespace ViewModels
09{
10    public class ForecastViewModel : ViewModel
11    {
12        private readonly IWebServiceClientFactory<IWeatherForecastService> weatherServiceFactory;
13 
14        public ForecastViewModel(IWebServiceClientFactory<IWeatherForecastService> weatherServiceFactory)
15        {
16            this.weatherServiceFactory = weatherServiceFactory;
17 
18            this.GetForecastCommand =
19                new DelegateCommand<DateTime>(
20                    date =>
21                    {
22                        this.StatusMessage = string.Format("Invoking web service with parameter {0}", date.ToString());
23                        this.weatherServiceFactory.Invoke(
24date,
25null,
26this.weatherServiceFactory.WebServiceInstance.BeginGetForecast,
27 
28this.weatherServiceFactory.WebServiceInstance.EndGetForecast,
29 
30this.OnResultReceived);
31 
32                    });
33 
34        }
35 
36        private void OnResultReceived(AsyncWebServiceCallResult<DailyForecast> asyncResult)
37        {
38            if (asyncResult.WasSuccessfull)
39            {
40                this.StatusMessage = "New forecast received ok.";
41                this.ForecastThatWasReceived = asyncResult.Result;
42 
43            }
44            else
45            {
46                this.ForecastThatWasReceived = null;
47                this.StatusMessage = "Error result received: Error description: " + asyncResult.Exception.Message;
48            }
49        }
50 
51        private IDelegateCommand getForecastCommand;
52 
53        public IDelegateCommand GetForecastCommand
54        {
55            get { return getForecastCommand; }
56            set { getForecastCommand = value;
57                this.OnPropertyChanged("GetForecastCommand");
58            }
59        }
60 
61        private DailyForecast forecastThatWasReceived;
62 
63        public DailyForecast ForecastThatWasReceived
64        {
65            get { return forecastThatWasReceived; }
66            set { forecastThatWasReceived = value;
67            this.OnPropertyChanged("ForecastThatWasReceived");
68            }
69        }
70 
71        public DateTime ValidForecastDate
72        {
73            get
74            {
75                return DateTime.Now;
76            }
77        }
78 
79        public DateTime BadForecastDate
80        {
81            get
82            {
83                return DateTime.MinValue;
84            }
85        }
86 
87        private string statusMessage;
88        public string StatusMessage
89        {
90            get { return statusMessage; }
91            set { statusMessage = value;
92            this.OnPropertyChanged("StatusMessage");
93            }
94        }
95    }
96}

As you can see from the ForecastViewModel we have a command that’s invoking the web service called GetForecastCommand and we have a action method OnResultReceived that receives the result.

If the web service call fails we set the ForecastThatWasReceived to null and we set the StatusMessage to the Message of the Exception we received from server.

So here is our simple ForecastView:

01<UserControl x:Class="Views.ForecastView"
02    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
03    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
04    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
05    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
06    mc:Ignorable="d"
07    d:DesignHeight="300" d:DesignWidth="400" MinHeight="400" MinWidth="400">
08 
09    <Grid x:Name="LayoutRoot" Background="Red">
10 
11        <Grid.RowDefinitions>
12            <RowDefinition></RowDefinition>
13            <RowDefinition></RowDefinition>
14            <RowDefinition></RowDefinition>
15        </Grid.RowDefinitions>
16        <StackPanel Orientation="Vertical" Grid.Row="0">
17            <Button Content="Invoke valid web service call" Command="{Binding GetForecastCommand}" CommandParameter="{Binding ValidForecastDate}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10" />
18 
19            <Button Content="Invoke web service call that throws exception on server" Command="{Binding GetForecastCommand}" CommandParameter="{Binding BadForecastDate}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10" />
20 
21        </StackPanel>
22 
23        <Grid Grid.Row="1">
24            <StackPanel Orientation="Vertical">
25                <TextBlock Text="{Binding ForecastThatWasReceived.Date, StringFormat='Date: {0}', FallbackValue=' ?'}" />
26                <TextBlock Text="{Binding ForecastThatWasReceived.Description, StringFormat='Description: {0}', FallbackValue=' ?'}" />
27 
28            </StackPanel>
29        </Grid>
30 
31        <Grid Grid.Row="2">
32            <TextBlock Text="{Binding StatusMessage}" TextWrapping="Wrap" />
33 
34        </Grid>
35 
36    </Grid>
37</UserControl>

As you can see we have two buttons, each wired up to the same GetForecastCommand but with different parameters.
One is sending the current date to the server and other is using the BadForecastDate databound from ViewModel which is set to DateTime.Min. When web service receives any other date then DateTime.Min it returns valid instance of DailyForecast class and if it receives DateTime.Min it throws some bogus exception.
This is how we will test our WebServiceFactory class to see if it can handle the exceptions thrown on server side or not.

you can test the live sample application here.

So here is screenshot of the app (in case you dont have the Silverlight 4 runtime installed) when we invoke the web service with current date:

As you can see when we click on first button we receive the valid forecast and when we click the second one, we will receive the error but it will be catched and wrapped in our AsyncWebServiceCallResult class and our UI won’t hang and we will be able to recover from that error and immediately invoke the web service call again with different parameters.

Here is the same app when we invoke the web service method with invalid (min) date so it throws exception:

So this should help us handle the web service with greater ease right ? 😀

But wait! We are not finished yet! Those of you that were paying attention noticed i promised a unit testable web services.

So lets do that also.

We will add another SIlverlight application to our sample code and set it up with Silverlight Unit Testing Framework.

Also we will reference all the needed projects – ViewModels, Abstractions.Silverlight, Framework.Abstractions and Framework.Implementors.

Also we need to make a fake WebServiceClientFactory and IWeatherService implementations so we can use them in our tests instead of the real implementations.

So lets do that first. here is the FakeWebServiceClientFactory:

01using System;
02using Abstractions;
03using Framework.Abstractions.Silverlight.WebServices;
04 
05namespace Silverlight.Tests
06{
07    public class FakeWebServiceClientFactory : IWebServiceClientFactory<IWeatherForecastService>
08    {
09        public FakeWebServiceClientFactory()
10        {
11            this.WebServiceInstance = new FakeWeatherService();
12        }
13 
14        public void Dispose()
15        {
16            throw new NotImplementedException();
17        }
18 
19        public IWeatherForecastService WebServiceInstance { get; private set; }
20 
21        public object LastParameterSentToInvoke;
22 
23        public object NextResultToReturn;
24 
25        public void Invoke<TParam, TResult>(TParam param, object state, Func<TParam, AsyncCallback, object, IAsyncResult> beginOp, Func<IAsyncResult, TResult> endOp, Action<AsyncWebServiceCallResult<TResult>> onComplete)
26        {
27            this.LastParameterSentToInvoke = param;
28 
29            var nextResult = NextResultToReturn as AsyncWebServiceCallResult<TResult>;
30 
31            if (nextResult != null)
32            {
33                onComplete(nextResult);
34            }
35            else
36            {
37                onComplete(new AsyncWebServiceCallResult<TResult>
38                               {Exception = new Exception("Some exception"), WasSuccessfull = false});
39            }
40        }
41    }
42}

As you can see it does not do much, its just a manually written mock class we can use in our test instead of the real web service client factory.
It allows us to check what was sent to the Invoke method as parameter and it allows us to set what will be sent to the OnComplete handler when client code invokes some web service call.

Also we need a stub for the IWeatherForecastService so here it is:

01using System;
02using Abstractions;
03 
04namespace Silverlight.Tests
05{
06    public class FakeWeatherService : IWeatherForecastService
07    {
08        public IAsyncResult BeginGetForecast(DateTime day, AsyncCallback callback, object state)
09        {
10            throw new NotImplementedException();
11        }
12 
13        public DailyForecast EndGetForecast(IAsyncResult result)
14        {
15            throw new NotImplementedException();
16        }
17    }
18}

Again its very simple its just a Stub class that allows us to instantiate and use it without really calling it.
So now we can write few tests for our ForecastViewModel:

01using System;
02using Abstractions;
03using Framework.Abstractions.Silverlight.WebServices;
04using Microsoft.VisualStudio.TestTools.UnitTesting;
05using ViewModels;
06 
07namespace Silverlight.Tests
08{
09    [TestClass]
10    public class ForecastViewModelTests
11    {
12        [TestMethod]
13        public void GetForecastCommand_WhenExecutedWithParam_InvokesCallOnWebServiceClientFactoryInstance()
14        {
15            var fakeFactory = new FakeWebServiceClientFactory();
16            var viewModel = new ForecastViewModel(fakeFactory);
17 
18            var date = DateTime.Now;
19 
20            viewModel.GetForecastCommand.Execute(date);
21 
22            Assert.AreEqual(date, fakeFactory.LastParameterSentToInvoke);
23        }
24 
25        [TestMethod]
26        public void GetForecastCommand_WhenExecutedWithMinDateANdWebserviceReturnsUnsuccessfullResult_SetsTheForecastThatWasReceivedToNull()
27        {
28            var fakeFactory = new FakeWebServiceClientFactory();
29            var viewModel = new ForecastViewModel(fakeFactory);
30            viewModel.ForecastThatWasReceived = new DailyForecast() {Description = "just dummy so we can test if it was set to null."};
31 
32            fakeFactory.NextResultToReturn = new AsyncWebServiceCallResult<DailyForecast>() {WasSuccessfull = false, Exception = new Exception("Bad error.")};
33            viewModel.GetForecastCommand.Execute(DateTime.MinValue);
34 
35            Assert.IsNull(viewModel.ForecastThatWasReceived);
36        }
37 
38        [TestMethod]
39        public void GetForecastCommand_WhenExecutedWithMinDateANdWebserviceReturnsUnsuccessfullResult_SetsTheStatusMessageToErrorFromReturnedException()
40        {
41            var fakeFactory = new FakeWebServiceClientFactory();
42            var viewModel = new ForecastViewModel(fakeFactory);
43            viewModel.ForecastThatWasReceived = new DailyForecast() { Description = "just dummy so we can test if it was set to null." };
44 
45            fakeFactory.NextResultToReturn = new AsyncWebServiceCallResult<DailyForecast>() { WasSuccessfull = false, Exception = new Exception("Bad error.") };
46            viewModel.GetForecastCommand.Execute(DateTime.MinValue);
47 
48            Assert.IsTrue(viewModel.StatusMessage.Contains("Bad error."));
49        }
50 
51        [TestMethod]
52        public void GetForecastCommand_WhenExecutedWithOkDateANdWebserviceReturnsSuccessfullResult_SetsTheStatusMessageToOkMessage()
53        {
54            var fakeFactory = new FakeWebServiceClientFactory();
55            var viewModel = new ForecastViewModel(fakeFactory);
56            viewModel.ForecastThatWasReceived = null;
57 
58            fakeFactory.NextResultToReturn = new AsyncWebServiceCallResult<DailyForecast>() { WasSuccessfull = true};
59            viewModel.GetForecastCommand.Execute(DateTime.Now);
60 
61            Assert.IsTrue(viewModel.StatusMessage.Contains("New forecast received ok."));
62        }
63 
64    }
65}

And when we run them, as you can see from the screenshot below, they are all GREEN!

So there you go, we have completed in this lengthy posts most of the tasks we set in the beginning. Off course there are many places for improvement but the basis of a simple way to invoke WCF web services from Silverlight and MVVM and Unit Testability are there.

If you have some comments and improvements to the solutions presented here i would be happy to hear them out.

You can download Visual Studio 2010 Solution with the code from this post if you want to run it locally.

Until then, happy testing!

18 thoughts on “Unit Testable WCF Web Services in MVVM and Silverlight 4

  1. That is some really nice work – the standard MS WCF service tool has been annoying me for ages – slow, creates reams of excess code etc. This is a great alternative.

  2. Nice articel, however the “#if SILVERLIGHT” within the interface really smells, don’t you think? You are talking about making code more testable but are at the same time creating hard to test code by using defines. Just my two “preprocessor usage is bad” cents.

  3. i noticed in the demo that the parameter used to send to the web service never changes per instance of the application.

    for instance, clicking the button to pass a valid parameter geturns DateTime.Now … but if i wait a minute and click it again, the date never changes.

    What’s that about?

    1. Hi Joe,

      it was logical error in WeatherForecastService.svc.cs where instead of returning DateTime.Now i was returning the date that is sent as parameter to the service.
      Its not very important since i was trying to prove that this can be unit tested but still its valid point.

      Thanks for finding this!

  4. Hi there,

    I just downloaded the sample and getting an error when trying to compile this.

    Error 1 The name ‘App’ does not exist in the current context SimpleServiceLocatorNavigationContentLoader.cs 37 20 Framework.Implementors.Silverlight

    has anyone seen this?

    Thank you

Leave a Reply to UR Cancel reply