Microsoft Fakes and WebChannelFactory (Unit Test for WCF Service)


Recently we wrote a plugin assembly that was calling a rest service using WebChannelFactory.

// wcf interface


public interface IAutoNumber
 /// <summary>
 /// Gets the next number.
 /// </summary>
 /// <param name="value">The value.</param>
 /// <returns>the next incremental value</returns>
 [WebGet(UriTemplate = "getsequencenumber/{value}")]
 string GetNextNumber(string value);

// plugin code

using (
 var webChannelFactory =
 new WebChannelFactory<IAutoNumber>(
 new Uri(dictionaryConfigSettings[Constants.AutoNumberServiceUrl])))
 IAutoNumber client = webChannelFactory.CreateChannel();
 // get the next number from sequence
 autoNumber = Constants.PrefixClient +

if (entity.Attributes.Contains("name"))
 // add the value to the name property bag input parameter for the client record being created
 entity.Attributes["name"] = autoNumber;
 entity.Attributes.Add("name", autoNumber);

Next we had to write the unit test case for the plugin using Microsoft Fakes. 
Below is the code that we used
using (ShimsContext.Create())
 ShimChannelFactory<IAutoNumber>.Constructor = factory => { };
 IAutoNumber autoNumber = new StubIAutoNumber
 GetNextNumberString = s => { return "12345"; }
 ShimChannelFactory<IAutoNumber>.AllInstances.CreateChannel = factory => { return autoNumber; };
 var preClientCreate = new PreClientCreate();

Hope it helps.

Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

Please share your thoughts

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.