Unit Testing REST Clients

I frequently seem to end up writing code that calls REST services – on pretty much every project I work on anymore.  Since I seem to be often writing the same code over and over, I’m working on a library (well a couple libraries) to simplify things and consolidate all that I typically come across.

A challenge in writing a REST client is how to easily unit test it.  I don’t want to have to stand up a server somewhere just to run simple tests, especially if the server needs to return valid and invalid data that needs to change with the test.

So I create a really simple, yet really useful class I’m calling SimpleServer and it’s available as a gist.  It basically allows you to define a URI and then set callback methods for the common HTTP verbs (GET, PUT, POST and DELETE).

Let’s say you want to test out a GET operation.  In the example below the RestConnector encapsulates the goo required to make the HTTP call, but the cool part is how it uses the SimpleServer to test an expected response to a GET at the API root.

        public void GetNoCreds()
            var uri = "http://localhost:8080/";
            var response = "Hello!";

            using (var svr = new SimpleServer(uri, (request) =>
                return response;

                using (var rc = new RestConnector(uri))
                    var result = rc.GetString("/");

                    Assert.AreEqual(response, result);

Here I’m using the default handler parameter for a GET, but you can individually pass in Func’s for GET, PUT, POST and DELETE which makes testing even fairly complex scenarios both quick and really, really easy.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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