How to unit test your API?

I am at the point where I need to write unit tests for the REST API, written using CakePHP 1.3. The API supports GET, POST, and PUT requests for requests and data processing.

Is there an established way to verify the correct I / O of an API simulating an HTTP request using fixtures ? I do not want to run the actual POST / PUT requests in the live (dev) database. How can I best mock a system to use temporary models, but check the rest of the stack as is?




Testing GET requests is quite simple with controller tests . However, for data processing, the API uses HTTP headers quite widely, and also parses raw XML and JSON POST / PUT data. Unit test controller methods only make fun of POST data by setting $this->data in the controller, which prevents me from testing the API correctly.

+48
api unit-testing cakephp
Jun 28 '10 at 2:55
source share
3 answers
+5
Jun 28 '10 at 3:14
source share

It looks like you can test the raw XML PUT and POST data without much trouble. The CakePHP REST documentation says the following:

If the POST or PUT request is of the XML content type, then the input is taken and passed to the Cake Xml object instance, which is assigned to the $ data property of the controller. Because of this function, the processing of XML and POST data is parallel: all changes are not required for the controller or model code. All you need should be in $ this-> data.

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

How to avoid a live database, will SQLite database in memory be easier?

+3
Jul 05 '10 at
source share

You must either create Mocks or use the Isolation Framework to model the API environment. Unit tests should not depend on resources such as Internet connections, network, endpoints, etc.

If you intend to test real API calls, you should create an integration project and use it for this purpose. But keep in mind that integration tests are mostly not repeated and give different results each time you run.

+3
Jan 13 '15 at 23:12
source share



All Articles