Software QA FYI - SQAFYI

In Process Http Server for Integration Test Faking with Owin, Katana, and WebAPI

By:

Sometimes when integration testing we need an HTTP endpoint. We can set one up in our solution (for example a Web Api project) and make sure it’s running before we execute our integration tests but it can be painful. Also consider when running on a build server, the web site will need to be provisioned, etc.

For isolated integration tests that require some HTTP endpoint we can create an HTTP endpoint from within our test code that doesn’t require a separate web project. This means that when tests run they have no external dependency in the sense of a “real” website being hosted somewhere – even if that somewhere is on the local dev machine. Another advantage of the approach outlined below is that because it’s all in-process it’s also faster than actually going through the network stack.

The System Under Test
We are going to test the following class that calls a service to change a string to uppercase:
using System;
using System.Net;
namespace ClassLibrary
{
public class ToUpperServiceGateway
{
private readonly string _serviceEndpoint;

public ToUpperServiceGateway(string serviceEndpoint)
{
_serviceEndpoint = serviceEndpoint;
}

public string MakeUppercase(string lowercase)
{
using (var wc = new WebClient())
{
return wc.DownloadString(_serviceEndpoint + "/" + lowercase);
}
}
}
}


This code uses WebClient to call a web service. In the integration tests we want to spin up a website that will return a mock value for example.

Writing the Initial Test Code
So an initial test could look somethine like:
using Xunit;
namespace ClassLibrary.IntegrationTests
{
public class UpperCaseTests
{
[Fact]
public void ShouldGetUppercase()
{
var sut = new
ToUpperServiceGateway("http://localhost:8084/api/toupper");

var upper = sut.MakeUppercase("hello");

Assert.Equal("HELLO", upper)
; }
}
}

If we run this we get “System.Net.WebException Unable to connect to the remote server” as we’d expect as there’s no website at the address.

Full article...


Other Resource

... to read more articles, visit http://sqa.fyicenter.com/art/

In Process Http Server for Integration Test Faking with Owin, Katana, and WebAPI