Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test your API?

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.

like image 454
deceze Avatar asked Jun 28 '10 02:06

deceze


People also ask

How do I unit test API?

An API test is similar to a unit test with a setup (prepare data for calling the API method), a call to the API method and then checking of the results. The semantics may require multiple calls to the API, producing tests that have more than one step.

Is it possible to unit test Web API?

We have an option to create a Unit test project when we create a Web API project. When we create a unit test project with a web API project, Visual Studio IDE automatically adds Web API project reference to the unit test project.


1 Answers

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.

like image 111
Teoman shipahi Avatar answered Sep 21 '22 00:09

Teoman shipahi