Skip to main content

Self hosting a web service inside a test fixture using WebAPI

I have a class which handles all the communication to any back-end RESTful service, it wraps up all the complexity of using HttpWebRequest and provides a simple API:

   1:  public interface IRestClient
   2:  {
   3:      Task<RestResponse<T>> GetAsync<T>(Uri url) where T : class;
   4:      Task<RestResponse> PutAsync<T>(Uri url, T resource) where T : class;
   5:      Task<RestResponse<T>> PostAsync<T>(Uri url, T resource) where T : class;
   6:      Task<RestResponse> DeleteAsync(Uri url);
   7:  }

The implementation of this class isn't relevant for this post - it's all about the behaviour. The behaviour is what I'm trying to test not the internal implementation...

So how can I test this in a standard test fixture?

I knew it was possible but I didn't think it would so easy...

Having used asp.net WebAPI for hosting services in IIS I knew this was the tech stack I wanted to use, but could it be used to host a service inside a custom process - any of the popular testing frameworks?

The answer is yes, you have to use the Web API Self Host NuGet package and then you only need 5 lines of code to have a service up and running inside any process:

   1:  var config = new HttpSelfHostConfiguration(_baseUrl);
   2:   
   3:  config.Routes.MapHttpRoute("DefaultAPI", "api/{controller}/{id}", new { id = RouteParameter.Optional });
   4:   
   5:  _server = new HttpSelfHostServer(config);
   6:  _server.OpenAsync()
   7:      .Wait();

The only difference from the test fixture point of view was instead of using a setup & tear-down per test, it will be per test fixture - per class. In the example below I'm using nUnit but you should be able to doing the equivalent in all the common testing frameworks:
You can see I'm setting up a HTTP service on port 8083, I use the explicit machine name instead of localhost so that I can observe the HTTP traffic in Fiddler. When you've more than one test fixture using self hosting you're going to need a unique port for each test fixture - this means if you run the tests in parallel you won't get any port conflicts.

You can also see the test controller I'm using - EmployeesController, from a testing point of view the I don't care about the actual data just that it can be serialized and sent over the wire. The controller is shown below and it has methods to support the common HTTP verbs - GET, POST, PUT &  DELETE...

It exposes the employees as a public static property so I can set it from the test fixture:

   1:  public class EmployeesController : ApiController
   2:  {
   3:      public static IList<Employee> Employees = new List<Employee>();
   4:          
   5:      public IEnumerable<Employee> GetAllEmployees()
   6:      {
   7:          return Employees;
   8:      }
   9:   
  10:      public HttpResponseMessage Get(int id)
  11:      {
  12:          var testHeader = Request.Headers.FirstOrDefault(h => h.Key == "TestHeader");
  13:              
  14:          var cookies = Request.Headers.GetCookies();
  15:          var testCookie = cookies.FirstOrDefault(c => c.Cookies.Contains(new CookieState("TestCookie")));
  16:   
  17:          var employee = Employees.FirstOrDefault((p) => p.Id == id);
  18:          if (employee == null)
  19:          {
  20:              throw new HttpResponseException(HttpStatusCode.NotFound);
  21:          }
  22:   
  23:          var response = Request.CreateResponse(HttpStatusCode.OK, employee);
  24:   
  25:          if (testHeader.Key != null)
  26:          {
  27:              response.Headers.Add("TestHeader", testHeader.Value);
  28:          }
  29:   
  30:          if (testCookie != null)
  31:          {
  32:              response.Headers.AddCookies(new[] { new CookieHeaderValue("TestCookie", testCookie["TestCookie"].Value) });
  33:          }
  34:   
  35:          return response;
  36:      }
  37:   
  38:      public void Put(int id, Employee employee)
  39:      {
  40:          var existEmployee = Employees.FirstOrDefault((p) => p.Id == id);
  41:          if (existEmployee == null)
  42:          {
  43:              Employees.Add(employee);
  44:          }
  45:          else
  46:          {
  47:              existEmployee.FirstName = employee.FirstName;
  48:              existEmployee.LastName = employee.LastName;
  49:          }
  50:      }
  51:   
  52:      public HttpResponseMessage Post(Employee employee)
  53:      {
  54:          var maxId = Employees.Max(e => e.Id);
  55:          var newId = ++maxId;
  56:   
  57:          employee.Id = newId;
  58:          Employees.Add(employee);
  59:   
  60:          var uri = Url.Link("DefaultApi", new { id = employee.Id });
  61:   
  62:          var response = Request.CreateResponse(HttpStatusCode.Redirect);
  63:          response.Headers.Location = new Uri(uri);
  64:          return response;
  65:      }
  66:   
  67:      public HttpResponseMessage Delete(int id)
  68:      {
  69:          var existEmployee = Employees.FirstOrDefault(p => p.Id == id);
  70:          if (existEmployee != null)
  71:          {
  72:              Employees.Remove(existEmployee);
  73:          }
  74:   
  75:          return new HttpResponseMessage(HttpStatusCode.NoContent);
  76:      }
  77:  }

So now I'm able to have a nice clean unit test:

   1:  [Test]
   2:  public void should_return_single_json_object()
   3:  {
   4:      // ARRANGE
   5:      var url = new Uri(_baseUrl + "/api/employees/1");
   6:   
   7:      // ACT
   8:      var task = _restClient.GetAsync<Employee>(url);
   9:      task.Wait();
  10:              
  11:      var employee = task.Result.Resource;
  12:              
  13:      // ASSIGN
  14:      Assert.That(employee, Is.Not.Null);
  15:      Assert.That(employee.Id, Is.EqualTo(_employees.First().Id));
  16:      Assert.That(employee.FirstName, Is.EqualTo(_employees.First().FirstName));
  17:      Assert.That(employee.LastName, Is.EqualTo(_employees.First().LastName));
  18:  }

And this gives the satisfying test output:
One thing to note is the setup of the service infrastructure takes sometime, this can been seen in the duration of the test 1.866 seconds. This only appears to apply to the first test fixture setup, shown below is the duration for 4 different test fixtures, each fixture has it's own service:
As you can see only the RestClient_DeleteTests takes any noticeable time to run...

So you can see it was relatively easy to get up and running, in fact it took less than 5 minutes...

Comments

  1. Seems to me your put method, at least as posted in this blogpost, is incorrect?

    If the existing employee is null, why add it? And assuming that statement should have been != then your else statement would throw an error since existEmployee is null?

    Seems that your test would work since you are assigning the static List, but try making a 'PUT' test where you do not assign your static propery, it should throw an exception on multiple coverage paths.

    Unless I am missing something here ;-)

    Regardless, great post, will surely help me in my testing endavours, cheers!

    ReplyDelete
    Replies
    1. Ah, I see it now, you probably meant to add 'employee' to the List ;-)

      Delete
    2. Yeah there was a mistake in the controller in the example - corrected that now.

      The controller is not the important part of the post really, but thanks for pointing it out

      Delete
  2. This comment has been removed by the author.

    ReplyDelete

Post a Comment

Popular posts from this blog

Showing a message box from a ViewModel in MVVM

I was doing a code review with a client last week for a WPF app using MVVM and they asked ' How can I show a message from the ViewModel? '. What follows is how I would (and have) solved the problem in the past. When I hear the words ' show a message... ' I instantly think you mean show a transient modal message box that requires the user input before continuing ' with something else ' - once the user has interacted with the message box it will disappear. The following solution only applies to this scenario. The first solution is the easiest but is very wrong from a separation perspective. It violates the ideas behind the Model-View-Controller pattern because it places View concerns inside the ViewModel - the ViewModel now knows about the type of the View and specifically it knows how to show a message box window: The second approach addresses this concern by introducing the idea of messaging\events between the ViewModel and the View. In the example below

Implementing a busy indicator using a visual overlay in MVVM

This is a technique we use at work to lock the UI whilst some long running process is happening - preventing the user clicking on stuff whilst it's retrieving or rendering data. Now we could have done this by launching a child dialog window but that feels rather out of date and clumsy, we wanted a more modern pattern similar to the way <div> overlays are done on the web. Imagine we have the following simple WPF app and when 'Click' is pressed a busy waiting overlay is shown for the duration entered into the text box. What I'm interested in here is not the actual UI element of the busy indicator but how I go about getting this to show & hide from when using MVVM. The actual UI elements are the standard Busy Indicator coming from the WPF Toolkit : The XAML behind this window is very simple, the important part is the ViewHost. As you can see the ViewHost uses a ContentPresenter element which is bound to the view model, IMainViewModel, it contains 3 child v

Custom AuthorizationHandler for SignalR Hubs

How to implement IAuthorizationRequirement for SignalR in Asp.Net Core v5.0 Been battling this for a couple of days, and eventually ended up raising an issue on Asp.Net Core gitHub  to find the answer. Wanting to do some custom authorization on a SignalR Hub when the client makes a connection (Hub is created) and when an endpoint (Hub method) is called:  I was assuming I could use the same Policy for both class & method attributes, but it ain't so - not because you can't, because you need the signatures to be different. Method implementation has a resource type of HubInnovationContext: I assumed class implementation would have a resource type of HubConnectionContext - client connects etc... This isn't the case, it's infact of type DefaultHttpContext . For me I don't even need that, it can be removed completely  from the inheritence signature and override implementation. Only other thing to note, and this could be a biggy, is the ordering of the statements in th