开发者

How to unit test your API?

开发者 https://www.devze.com 2023-01-04 18:20 出处:网络
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.

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 a开发者_开发问答ctual 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.


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.


I'd recommend starting with a little research. These articles should help:

  • Unit Testing CakePHP Shells
  • Testing CakePHP controllers - Mock Objects edition
  • Testing Models with CakePHP 1.2 test suite


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消