Skip to content

Writing Integration Tests

Emma Corbett edited this page Jun 25, 2020 · 11 revisions

Writing integration tests

When creating a new endpoint or adding new functionality to an API it's good practice to start by writing an integration test outlining the functionality you are hoping to achieve. You can then write unit tests when you touch the individual classes you will be working on. Integration tests give you confidence that all your classes work together and that the full feature you have made is working correctly.

To write Integration tests, inherit the IntegrationTest class for some useful test setup.

public class ExampleTest : IntegrationTests<Startup> {
  //...your tests here
}

This will set up a web application factory so that you can make calls to endpoints, for example

var uri = new Uri($"api/v1/residents/{personId}", UriKind.Relative);
var response = Client.GetAsync(uri);

It will also set up a database connection and register it in a mock startup class. You can also use this connection in the test setup if you need to add anything to the database to test against.

An example of an integration test for a GET endpoint would be to add entities to the database and then assert they get returned in the response from the endpoint. Here is a simplified example of this.

var person = new DatabaseEntity { Id = 1, Name = "Henry" };
DatabaseContext.DatabaseEntities.Add(person);
DatabaseContext.SaveChanges()

var response = Client.GetAsync( new Uri($"api/v1/residents", UriKind.Relative));

var expectedJsonResponse = "{ residents: [{ "id": 1, "name": "Henry"  }] }";

response.Result.Content.Should().Be(expectedJsonResponse);

Clone this wiki locally