Testing multiple API contracts as part of 1 test

I have a situation whereby, say, I have one API which creates an employee(POST); one which then returns the employee(GET) and one which deletes the employee(DELETE).

I’ve been using RestSharp/C# to create my API tests which I’ve found really useful, however I’m struggling to understand how I’d create a test like the above where I’d want to test multiple API’s as part of the one test so that I can ensure the creation and deletion works as expected.

If anyone has any advice or working examples of this, it would be very useful

I would tend to suggest that you split these into three separate test cases rather than one.

If you were to put all three tests you mention above (POST, GET, DELETE) into one test and the DELETE failed, then your test case would not cleanly distinguish which of scenarios failed, you would have to dig into your test failure to uncover that.

Ideally you would want be able to replace the persistence layer that your API is writing to (e.g. a database) and replace it with a Test Double. This way you can cleanly assert that your API behaves in each individual test case as it should.

So in the example of your GET test case. Your test case would setup your API and replace the persistence layer with a Stub that when called will return a valid representation on an employee. You can then call your API with an HTTP GET Request and assert that it has a valid Response (status code 200) and contains the employee data that you had your DB stub pass to it.

This also then allows you to make another test case for GET but have the Stub pass back no employee data to represent the fact there isn’t an employee in the DB. Your test case can then assert that your API handles this gracefully and passes back a nice Response (status code 404).

This approach is a little more work and involves setting up the ability to replace the API dependencies with Test Doubles but it allows for really nice granular tests and reduces brittleness.

Hope this helps.

1 Like

That’s great, thank you Rob. The concept of a Test Double and the persistence layer are new concepts to me; would you mind elaborating a bit further for me on these?

Also, with a stub is this something you would create yourself in code, or would you import a tool to do this for you?