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:
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:
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:
So now I'm able to have a nice clean unit test:
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...
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...
Seems to me your put method, at least as posted in this blogpost, is incorrect?
ReplyDeleteIf 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!
Ah, I see it now, you probably meant to add 'employee' to the List ;-)
DeleteYeah there was a mistake in the controller in the example - corrected that now.
DeleteThe controller is not the important part of the post really, but thanks for pointing it out
This comment has been removed by the author.
ReplyDelete