Alica's dev blog
Integration tests with ASP.NET Core and SQL Server - Part 5: Put it all together

After the first four parts (part 1, part 2, part 3, part 4), we now have all the elements ready and finally are able to run the tests.

Initialise the database

In TestApplicationFactory, we add a property TestDatabase and perform the initialisation in ConfigureWebHost method:

builder.ConfigureServices((context, collection) =>
{
	// read from the configuration
	var connectionString = context.Configuration.GetConnectionString("Local");
	// initialise the DB
	TestDatabase = new TestDatabase(connectionString);
	TestDatabase.Initialise();
});

Run a pre-test setup

Then, we add TestConfig class with two static properties: TestDatabase and HttpClient. Those properties will later be used directly in the tests.

SetUpFixture is NUnit-specific attribute that marks the class that contains OneTimeSetUp method which will be called only once. Feel free to replace them with similar constructs of your preferred test framework.

[SetUpFixture]
public class TestConfig
{
	public static TestDatabase TestDatabase { get; private set; }
	public static HttpClient HttpClient { get; private set; }
	
	[OneTimeSetUp]
    public void SetUp()
    {
		var testApplicationFactory = new TestApplicationFactory();
		HttpClient = testApplicationFactory.CreateClient();
		TestDatabase = testApplicationFactory.TestDatabase;
    }
}

Add tests!

A very simple example is the one where we try to send GET request for a book that doesn’t exist, and want to check if the operation returns 404.

public void GetBook_NonExisting_ReturnsNotFound()
{
	// send the request
	var response = TestConfig.HttpClient.GetAsync("api/books/12345");
	
	// check if the response code is correct
	response.AssertNotFound();
}

Or a more complicated one, where we actually make use of the database: Let’s check if the GET request for a book with specific ID returns correct result.

public void GetBook_IsSuccessful()
{
	// run a custom script that seeds the database
	TestConfig.TestDatabase.RunDbScript("TestSeed.sql");

	// send the request
	var response = TestConfig.HttpClient.GetAsync("api/books/1");
	
	// check if the response code is correct and obtain the result
	var book = response.AssertOk<Book>();

	// check if the response is correct
	book.Id.Should().BePositive();
	book.Name.Should().Be("Brave New World");
	book.Author.Should().Be("Aldous Huxley");
	book.YearPublished.Should().Be(1932);

	// clean up
	TestConfig.TestDatabase.CleanData();
}

And that’s it!

I am not sure whether I should wish you not to discover any bugs (assuming that you write perfect code), or to discover as many bugs as possible (assuming that you are a human, therefore your code contains bugs, and you want to discover them as early as possible).

One way or another, I wish you happy testing!

Source Code

You can view the complete source code on Github.

Previous parts


Last modified on 2020-11-06