With WCF we now can self-host a service which gives us some new options in regard to testing.
Howard van Rooijen in his blog offered a solution (Configuring WCF services for Unit Testing) which created an internal ServiceHost wrapper class for a new instance of the service host for testing. Though this solution worked there was a couple of areas where I thought it could be improved.
What I have done is:
a) remove the need for creating and maintaining a configuration file
b) move the whole thing into a seperate generic class ( called ServiceManager) which the contract and service as type parameters.
c) simplifying the the set-up process so it is more "set and forget" for a set of tests
d) incorporated the ChannelFactory creation into the class.
The code for this can be downloaded from the following link: Service manager for WCF tests.
To use the ServiceManager class we first create an instance of it:
[TestClass]
public class WebServiceIntegrationTests
{
static string baseAddress = @"http://localhost:8000/WebServiceTests";
static ServiceManager<IPeopleService, PeopleServiceType> serviceManager =
new ServiceManager<IPeopleService, PeopleServiceType>(baseAddress);
Having do that we then add the following code to the class initialise and cleanup methods:
[ClassInitialize()]
public static void ClassInitialize(TestContext testContext)
{
serviceManager.StartService();
}
[ClassCleanup()]
public static void ClassCleanup()
{
serviceManager.StopService();
}
[TestMethod]
public void GetNewPersonFromService()
{
string firstName = "Bob";
string lastName = "Builder";
int age = 35;
RelationshipType relation = RelationshipType.Business;
using (var factory = serviceManager.GetChannelFactory())
{
IPeopleService client = factory.CreateChannel();
Person person = client.GetNewPerson(firstName, lastName, age, relation);
Assert.AreEqual<string>(firstName, person.FirstName);
Assert.AreEqual<string>(lastName, person.LastName);
Assert.AreEqual<int>(age, person.Age);
Assert.AreEqual<RelationshipType>(relation, person.Relationship);
}
}