Daniel Cazzulino's Blog : Making WCF services amenable to testing

Subscriptions

News

Source code published in this blog is public domain unless otherwise specified.

 

kzu in LinkedIn

  Microsoft MVP Profile

 Contact

Post Categories

Making WCF services amenable to testing

You know that using WebOperationContext.Current is BAD for making your service implementation testable, don't you?

My friend Pablo Cibraro continued to evolve his ideas around decoupling your service implementation from this static dependency, and came up with the most simple yet totally unobtrusive (for production code) approach to this, which he calls WCFMock.

The idea is quite simple: you can leverage C# class aliasing functionality (which few know it even exists) to conditionally (i.e. DEBUG vs RELEASE builds) replace the WebOperationContext implementation, like so:

#if DEBUG
using WebOperationContext = System.ServiceModel.Web.MockedWebOperationContext;
#endif

What will happen here is that on DEBUG builds, the actual class invoked when your code calls WebOperationContext.Current will be different, and it will be the one that allows easy testability by providing interfaces for the context and all its properties. You can setup this mock context quite easily in your tests:

Mock mockContext = new Mock { DefaultValue = DefaultValue.Mock };
 
using (new MockedWebOperationContext(mockContext.Object))
{
  var formatter = catalog.GetProducts("foo");
}

// Just making sure the content type was properly set 
mockContext.VerifySet(c => c.OutgoingResponse.ContentType = "application/atom+xml");

 

Of course, WCF service implementations, in my opinion, should not contain much core, and be basically a REST/webservices facade on top of the actual implementation which is something that never depends on any WCF specifics. But for those cases where you must ensure some behavior from your service implementations, this is certainly the best way to do it.

posted on Tuesday, March 10, 2009 1:29 PM by kzu

# Making WCF services amenable to testing @ Tuesday, March 10, 2009 1:34 PM

You know that using WebOperationContext.Current is BAD for making your service implementation testable

Anonymous

# Making WCF services amenable to testing - Daniel Cazzulino's Blog @ Tuesday, March 10, 2009 2:11 PM

Thank you for submitting this cool story - Trackback from DotNetShoutout

Anonymous

# Daniel Cazzulino's Blog : Making WCF services ... @ Friday, April 03, 2009 5:00 PM

Bookmarked your post over at Blog Bookmarker.com!

Anonymous