How to use Pex and Moles to generate unit tests for a project having external dependency(WCF Proxy) using Visual Studio 2010 SP1
Source Code:
In this post I’ll discuss about writing unit tests using Pex and Moles. Pex and Moles are Visual Studio 2010 Power Tools that help Unit Testing .NET applications.
- Pex automatically generates test suites with high code coverage. Right from the Visual Studio code editor, Pex finds interesting input-output values of your methods, which you can save as a small test suite with high code coverage.
- Moles allows to replace any .NET method with a delegate. Moles supports unit testing by providing isolation by way of detours and stubs i.e. Generate a Mole type from the original type and redefine its behavior using delegates.
Pex and Moles can be downloaded from https://research.microsoft.com/en-us/projects/pex/.
I’ll explain the steps to generate unit tests for a project which calls a WCF service. Pex will be used to generate unit tests. Moles will be generated to isolate the external dependency(WCF proxy) and behavior will be redefined using delegates.
The projects inside the sample solution are
- DemoService: This project is a WCF Service.
- DemoLibrary: This project is a Class library and service reference to DemoService has been added. Unit tests will be generated for this project.
- ConsoleApp: This project is a Console application.
- DemoLibrary.Tests: This is a Test project and contains unit tests for DemoLibrary.
The solution structure is displayed below
DemoLibrary calls DemoService though proxy as displayed in the Layer diagram
I’ll now discuss in brief the code snippets of each project
WCF Service(DemoService): This service provided only a single operation
[ServiceContract]
public interface IDemoService
{
[OperationContract]
string Search(string criteria);
}
WCF Service Client(DemoLibrary): It calls the Search method of DemoService through proxy as displayed below
public string GetResults(string s)
{
DemoServiceReference.DemoServiceClient client = null;
try
{
client = new DemoServiceReference.DemoServiceClient();
client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
client.ChannelFactory.Credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
s = client.Search(s);
return s;
}
finally
{
if (client != null)
{
if (client.State == CommunicationState.Opened)
{
client.Close();
}
else if (client.State == CommunicationState.Faulted)
{
client.Abort();
}
}
}
}
Unit Testing DemoLibrary using Pex and Moles:
In order to generate unit tests for WCF Service Client(DemoLibrary) project the steps are
Right click on the class for which unit tests needs to be generated and click “Create Parameterized Unit Tests” as displayed below
A popup will be displayed where Filters and Output can be modified. Click Ok to go to next step.
A new test project will be created. Test Class and Test stub will be be added to this project as displayed below
/// <summary>This class contains parameterized unit tests for Search</summary> [PexClass(typeof(Search))] [PexAllowedExceptionFromTypeUnderTest(typeof(InvalidOperationException))] [PexAllowedExceptionFromTypeUnderTest(typeof(ArgumentException), AcceptExceptionSubtypes = true)] [TestClass] public partial class SearchTest { /// <summary>Test stub for GetResults(String)</summary> [PexMethod] public string GetResults([PexAssumeUnderTest]Search target, string s) { string result = target.GetResults1(s); return result; // TODO: add assertions to method SearchTest.GetResults(Search, String) } }
There is an external dependency(GetResults makes a service call though the WCF Proxy) so “Run Pex Explorations” will not generate unit tests as displayed below
In order to isolate the external dependency we need to generate Moles before running Pex Explorations. Moles will be generated for DemoLibrary and System.ServiceModel assemblies and behavior will be redefined using delegates. There are two ways to generate a mole for an assembly. I’ll show you both the approaches
Visual Studio: This is the easiest way.
Command Prompt: Moles can be generated from the command prompt.
Similarly as explained above we need to generate Moles for System.ServiceModel assembly. For Visual Studio 2010 SP1 this may fail with error message “The type or namespace name 'IHttpCookieContainerManager' does not exist in the namespace 'ssm::System.ServiceModel.Channels' (are you missing an assembly reference?)”. This step however works fine for Visual Studio 2010. The fix is to exclude the type i.e. 'IHttpCookieContainerManager' from StubGeneration as displayed below
The next step is to Mock the Service call(redefine behavior using delegates) and add Asserts as displayed in code snippets below
/// <summary>Test stub for GetResults(String)</summary> [PexMethod] public string GetResults([PexAssumeUnderTest]Search target, string s) { MockWCFService<IDemoService>(); MDemoServiceClient.Constructor = (var1) => new MDemoServiceClient { }; MDemoServiceClient.AllInstances.SearchString = (var1, var2) => { return "Result"; }; string result = target.GetResults(s); PexAssert.IsNotNullOrEmpty(result); PexAssert.AreEqual(result, "Result"); return result; } /// <summary> /// Mocks the WCF service. /// </summary> private void MockWCFService<TService>() where TService : class { MClientCredentials.Constructor = (var1) => new MClientCredentials() { WindowsGet = () => { return new MWindowsClientCredential(); } }; MClientCredentials.AllInstances.WindowsGet = (var1) => { return new MWindowsClientCredential(); }; MWindowsClientCredential.AllInstances.ClientCredentialGet = (var1) => { return new System.Net.NetworkCredential(); }; MWindowsClientCredential.AllInstances.ClientCredentialSetNetworkCredential = (var1, var2) => { }; MWindowsClientCredential.AllInstances.AllowNtlmGet = (var1) => { return true; }; MWindowsClientCredential.AllInstances.AllowNtlmSetBoolean = (var1, var2) => { }; MWindowsClientCredential.AllInstances.AllowedImpersonationLevelGet = (var1) => { return System.Security.Principal.TokenImpersonationLevel.Impersonation; }; MWindowsClientCredential.AllInstances.AllowedImpersonationLevelSetTokenImpersonationLevel = (var1, var2) => { }; MChannelFactory.AllInstances.CredentialsGet = (var1) => { return new MClientCredentials(); }; MClientBase<TService>.AllInstances.ClientCredentialsGet = (var1) => { return new System.ServiceModel.Description.ClientCredentials(); }; MClientBase<TService>.AllInstances.ChannelFactoryGet = (var1) => { return new MChannelFactory01<TService>(); }; MClientBase<TService>.AllInstances.StateGet = (var1) => { return PexChoose.EnumValue<CommunicationState>("CommunicationState"); }; MClientBase<TService>.AllInstances.Close = (var1) => { }; MClientBase<TService>.AllInstances.Abort = (var1) => { }; }
Run Pex Explorations to generate unit tests for GetResults method as displayed below
Unit tests will be added to the Test Class as displayed below
Summary:
In a similar way we can extract out external dependencies using Moles and then run Pex Explorations. A few examples of external dependencies can be data layer, UI layer, server calls etc. You can read more about Pex and Moles at https://research.microsoft.com/en-us/projects/pex/.
Comments
- Anonymous
May 02, 2012
In this post I’ll explain the steps to generate unit tests for a project which calls a WCF service using