How to unit test your API?

Unit TestingApiCakephp

Unit Testing Problem Overview


I'm at the point where I need to write unit tests for a REST API written using CakePHP 1.3. The API supports GET, POST and PUT requests for querying and manipulating data.

Is there any established way to test the correct input/output of an API simulating an HTTP request, using fixtures? I do not want to run actual POST/PUT requests against the live (dev) database. How can I best mock out the system to use temporary models, yet test the rest of the stack as-is?


Testing GET requests is easy enough with controller tests. However, for data manipulation the API uses HTTP headers quite extensively and also parses raw XML and JSON POST/PUT data. The controller unit test methods only mock POST data by setting $this->data in the controller, which does not allow me to properly test the API.

Unit Testing Solutions


Solution 1 - Unit Testing

You should either create Mocks or use Isolation Framework in order to simulate API environment. Unit tests should not depend on resources like internet connections, network, endpoints etc.

If you intend to test real API calls you should create integration test project and use it for this purpose. But be aware integration tests are mostly not repeatable and would give you different results on each run.

Solution 2 - Unit Testing

Solution 3 - Unit Testing

Looks like you might be able to test the raw XML PUT and POST data without too much trouble. The CakePHP REST documentation says this:

>If a POST or PUT request has an XML content-type, then the input is taken and passed to an instance of Cake's Xml object, which is assigned to the $data property of the controller. Because of this feature, handling XML and POST data in parallel is seamless: no changes are required to the controller or model code. Everything you need should end up in $this->data.

Try stepping through your controller code in debug mode to see what actually comes in through $this->data during an XML request.

As for avoiding the live database, would a SQLite in-memory database be any easier?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondecezeView Question on Stackoverflow
Solution 1 - Unit TestingTeoman shipahiView Answer on Stackoverflow
Solution 2 - Unit TestingCraig TraderView Answer on Stackoverflow
Solution 3 - Unit TestingDon KirkbyView Answer on Stackoverflow