Unit Testing WCF with Isolator – The Server

WCF actually cries out for unit testing. How can you make sure your logic actually works without relying on a response from a server? What happens when something happens on the wire? All kind of happenings make your tests not-repeatable.

And how is your logic handling what’s happening on the wire? A timeout for example. How do you test that? And finally, on the server side, how do you simulate issues that should come from the client or the wire?

You already know the answer.

Our example is simple. We have a single method we’re calling on the server side. Let’s take a look at the server code:

[ServiceContract(Namespace="http://AnyServer")]
public interface ISourceListProvider
{
 [OperationContract]
 string GetSourceList(string source);

}

and here’s the server code of our XMLProvider:

public string GetSourceList(string source)
{
 MessageHeaderInfo headerInfo = OperationContext.Current.IncomingMessageHeaders[0];
 if (headerInfo.Name != "ID")
 {
     throw new ArgumentException("Bad Header Info");
 }
 return "<SourceList><Source value="+source+"/></SourceList>";
}

I would like to test this method, based on it’s header. In this case I want to check the Name of the header info. With Isolator, here’s a test:

[TestMethod]
[Isolated]
public void GetData_SimulateGoodMessageHeader()
{
 Isolate.Fake.StaticMethods<OperationContext>();
 MessageHeaderInfo fakeInfo = Isolate.Fake.Instance<MessageHeaderInfo>();
 Isolate.WhenCalled(() => fakeInfo.Name).WillReturn("ID");
 Isolate.WhenCalled(() => OperationContext.Current.IncomingMessageHeaders[0]).WillReturn(fakeInfo);

 XMLProvider provider = new XMLProvider();
 string result = provider.GetSourceList("MySource");

 Assert.AreEqual(@"<SourceList><Source value=MySource/></SourceList>", result);
}

This is a simple test, with a simple setup – we fake the static calls (which will be out shortly in version 5.1), fake a MessageHeaderInfo object, and inject a name to satisfy the logic and confirm the result.

Now let’s see what happens if we get a bad message header. This time we expect an exception to occur:

[TestMethod]
[ExpectedException(typeof(ArgumentException))]
[Isolated]
public void GetData_SimulateBadMessageHeader()
{
 Isolate.Fake.StaticMethods<OperationContext>();
 MessageHeaderInfo fakeInfo = Isolate.Fake.Instance<MessageHeaderInfo>();
 Isolate.WhenCalled(() => fakeInfo.Name).WillReturn("Error");
 Isolate.WhenCalled(() => OperationContext.Current.IncomingMessageHeaders[0]).WillReturn(fakeInfo);

 WCFServer.XMLProvider provider = new WCFServer.XMLProvider();
 string result = provider.GetSourceList("MySource");
}

Simple, isn’t it? And this is on the server side. Next time, we’ll look at how we unit test the client side.

Want to start unit testing? Take advantage of our 30-day FREE trial of Isolator Complete. Get it now

  • Dmalesd

    Hi,
    I like the code examples but the code snippets don’t format properly on chrome,firefox,IE9

TOP