Start testing your API with CodeCeption

This is a brief step by step guide to install CodeCeption on your local machine and to create a basic but useful test for a fictional ‘Categories’ API endpoint.

Codeception is a Testing framework that you can use for creating Unit Tests, Acceptance tests and Web Services/API tests too. For more information, http://codeception.com/

The test created below makes sure an API endpoint such as http://api.domain.com/categories is online and responding as expected. It tests for a HTTP 200 code in the response, that the response is in a JSON format and that the response contains ‘success’.

This same test could be recreated for many other endpoints in your API. Also, If you store your code using Github or Bitbucket, you could use a service such as http://codeship.io or https://circleci.com/ to run those tests automatically any time you commit a change to your code to let you know that all of your API endpoints are online and responding as expected and only deploy changes Live if all your tests pass.

  1. Download codecept.phar from http://codeception.com/ and place it in the root of your project
  2. In the terminal, in the root folder, write ‘php codecept.phar bootstrap’, this creates the Tests folder and other bootstrap related files
  3. In the terminal, write ‘php codecept.phar generate:suite api ApiGuy’, this creates the /test/api folder where we will keep our API tests.
  4. Update the existing file called /tests/api.suite.yml with the code written below to give CodeCeption some basic information about our API, replacing ‘domain.com’ with your own URLs.
  5. In the terminal, write ‘php codecept.phar build’ to build the classes that we will need
  6. In the terminal, wite ‘php codecept.phar generate:cept api Categories’ to create a ‘Categories’ test in /tests/api/CategoriesCept.php
  7. Update CategoriesCept.php with the code below to tell it what to test.
  8. Finally, In the terminal, write ‘php codecept.phar run’ to run your tests!

api.suite.yml

class_name: ApiGuy
modules:
      enabled: [PhpBrowser, REST, ApiHelper]
      config:
            PhpBrowser:
                  url: http://domain.com/
            REST:
                  url: http://api.domain.com/

CategoriesCept.php

<?php
$I = new ApiGuy($scenario);
$I->wantTo(‘Return all categories’);
$I->sendGet(‘categories’);
$I->seeResponseCodeIs(200);
$I->seeResponseIsJson();
$I->seeResponseContains(“success”);
?>

2 Comments

  1. This isn’t working:

    [CodeceptionExceptionModuleRequireException]
    [REST] module requirements not met —

    This module depends on CodeceptionLibInnerBrowser

    Example configuring PhpBrowser as backend for REST module.

    modules:
    enabled:
    – REST:
    depends: PhpBrowser
    url: http://localhost/api/

    Framework modules can be used for testing of API as well.

Leave a Reply

Your email address will not be published. Required fields are marked *