Click here to Skip to main content
15,885,366 members
Articles / Programming Languages / C#

Frictionless WCF service consumption in Silverlight - Part 3: Benefits of transparent asynchrony with respect to unit testing

Rate me:
Please Sign up or sign in to vote.
4.78/5 (5 votes)
26 May 2011MIT15 min read 25.1K   259   11  
Simplifying unit testing of View Models which use asynchronous WCF service calls.
using System.Collections.ObjectModel;

using Microsoft.Silverlight.Testing;
using Microsoft.VisualStudio.TestTools.UnitTesting;

using Sample.Silverlight.WCF.Infrastructure;
using Sample.Silverlight.WCF.Web.Services;
using Sample.Silverlight.WCF.Tests.Clumsy.ServiceReference1;

namespace Sample.Silverlight.WCF.Tests.Clumsy
{
	public class TaskManagementViewModel : ViewModelBase
	{
		Task selected;

		public TaskManagementViewModel()
		{
			Tasks = new ObservableCollection<Task>();
		}

		public ObservableCollection<Task> Tasks
		{
			get; private set;
		}

		public Task Selected
		{
			get { return selected; }
			set
			{
				selected = value;
				NotifyOfPropertyChange(() => Selected);
			}
		}

		public void Activate()
		{
			var service = new TaskServiceClient();

			service.GetAllCompleted += (o, args) =>
			{
				if (args.Error != null)
					return;

				foreach (Task each in args.Result)
				{
					Tasks.Add(each);
				}

				Selected = Tasks[0];
			};
			
			service.GetAllAsync();
		}
	}

	[TestClass]
	public class TaskManagementViewModelFixture : SilverlightTest
	{
		[TestMethod]
		[Asynchronous]
		public void Should_query_service_for_current_tasks_on_first_activation()
		{
			// arrange
			var model = new TaskManagementViewModel();

			// this will be used as a wait handle for test completion 
			bool eventRaised = false;
			model.PropertyChanged += (o, args) =>
			{
				if (args.PropertyName == "Selected")
					eventRaised = true;
			};

			EnqueueConditional(() => eventRaised);

			// act
			model.Activate();

			// assert
			EnqueueCallback(() =>
			{
				Assert.AreEqual(2, model.Tasks.Count);
				Assert.AreSame(model.Tasks[0], model.Selected);
			});

			EnqueueTestComplete();
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer http://blog.xtalion.com
Ukraine Ukraine
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions