Microsoft’s ASP.Net Web API 2.2 allows you to easily create REST style APIs on an IIS website. Microsoft has some great documentation on how to get started with it, so I won’t rehash that here. Instead, I’m going to go a little deeper into some powerful features that can be used with Web API.
A few weeks ago I wrote an article called Cleaning Up EF 6 Tests With Transactions Rollbacks, where I showed how to create integration tests that set up some data in a database, run a test against the data, and then roll back all changes to the data. The rollback was possible because all of the changes to the data were wrapped up inside a transaction.
This posts extends that idea, but instead of a test calling methods on a repository or service layer, this test makes an HTTP call against a Web API endpoint, while preserving the ability to revert all changes to the database as part of a transaction rollback.
The interesting part here is that we will create a database context, start a transaction against that context, create some test data, and then spin up a Web API server that uses that same context. When we’re done with our tests, we’ll roll back the transaction so that the database changes are all reverted.
2016-01-27 Update - clarified when Configuration is available in an API Controller