Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing REST APIs using PHPUnit

Tags:

rest

php

phpunit

I am building a set of RESTful APIs and am now required to write unit tests for them. I am not sure what the unit tests should actually test.

Should unit tests check whether the response being received from the server is correct for various inputs? If so, is it a good practice to have a set of correct response formats pre-defined and check the responses against them?

UPDATE

I am calling these services through CURL and I can definitely check status code. The response may vary for different inputs, so should I check for all possible responses?

How is unit testing usually done for RESTful APIs using PHPUnit in general?

like image 799
Harsha Avatar asked Sep 16 '12 09:09

Harsha


1 Answers

If your API's data layer is sufficiently abstracted, so that you can receive consistent and predictable output for a given input, your test cases should definitely include some common output expectations for some finite list of inputs They should also test for any error cases you can drum up.

If your API can't run against a data layer that's in a predictable state (for example, if it's connected to live data, or to data that's shared among developers), you're going to end up spending a lot of time fixing your tests to correctly model the new state of the data. That makes unit testing less valuable, since you might not run them as often, and since you've never sure whether a test failure is due to a change in the data or a change in the program logic. Whether that outweighs the risk of not having unit tests or not will depend on your individual situation (how often do the tests break, how critical is the service, &ct).

As far as how to use PHPUnit to run test cases, I can't answer that specifically, but I imagine that you'd do as @basiljames noted; execute a call against a given endpoint and verify that the response received correctly matches your expectations. Not that different from any other unit test, except for the fact that they may run a little more slowly.

like image 50
cori Avatar answered Oct 24 '22 12:10

cori