Testing REST APIs Using PHPUnit

I am creating a RESTful API set, and now I need to write unit tests for them. I am not sure that the tests should actually be checked.

Should unit tests verify that the response from the server to different inputs is correct? If so, is it advisable to have a predetermined set of correct response formats and check the answers to them?

UPDATE

I call these services through CURL and I can definitely check the status code. The answer may vary for different inputs, so should I check all possible answers?

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

+8
rest php phpunit
source share
2 answers

If your API data level is abstracted enough so that you can get consistent and predictable results for a given input, your test cases should definitely include some general expected results for some final list of inputs. They should also check for any cases of errors you may drum.

If your API cannot work with a data layer that is in a predictable state (for example, if it is connected to current data or to data used by developers), you are going to spend a lot of time for your tests to correctly model the new data state. This makes unit testing less valuable, because you cannot run them as often, and since you never know if a crash occurred as a result of a data change or a change in the program logic. If this outweighs the risk of lack of unit tests or not, it will depend on your individual situation (how often the tests pass, how critical the service is, etc.).

As far as I can use PHPUnit to run test cases, I cannot answer this specifically, but I assume you will, as @basiljames noted; Make a call against this endpoint and make sure that the answer you receive matches your expectations correctly. This is no different from any other unit test, except that they may work a little slower.

+4
source share

You can use JUnit for your test cases. You will need to check the HTTP Status Code , and then the contents of the response for any specific attribute or value.

+2
source share

All Articles