Member-only story

How to properly test your HTTP API contracts in .NET

--

As I’m a Test Driven Development practitioner (with conviction), I regularly have to create automated tests that include the HTTP API of a module or component. Whether you call that a unit, integration or component test is debatable, but is beyond the point of this post. What I do care about that is that your tests only interact with the surface area designed for your production code. So if a particular part of your system is only invoked through an HTTP API, then your test should be doing the same thing. Directly invoking a method on an ASP.NET Controller class would violate that idea.

Another important principle which I follow in my testing endeavors is to ensure you only assert what is relevant for that particular test case. If you expect an exception, ensure it is the right type of exception, that its properties have the right value, and that its message matches your expectation. But with respect to the exception message, you only want to assert the relevant parts of that message. Fluent AssertionsWithMessage assertion takes a wildcard for that exact reason. Similarly, if your API is supposed to return a particular HTTP error code, only assert that it does and ignore the payload. If your test covers a particular path where only a specific property of the body is relevant, ignore the rest. This avoids failing tests for unrelated issues.

--

--

Dennis "The Continuous Improver" Doomen
Dennis "The Continuous Improver" Doomen

Written by Dennis "The Continuous Improver" Doomen

Dennis is a veteran architect in the .NET space with a special interest in writing clean code, Domain Driven Design, Event Sourcing and everything agile.

No responses yet