Functional tests for REST interfaces in yii 2

Just to cite a few of the features available, you’ll have functions to set and read headers, such as seeHttpHeader() and haveHttpHeader(), and specific methods to call HTTP requests towards our interface, such as sendGET(), sendPUT(), and sendOPTIONS().

Specifically for our interface of the user, our tests will be split into two parts:

  • Tests on the actual functionality—authentication and interaction with the application
  • Some additional tests to ensure that we are exposing the right endpoints

Now, with this in mind, let’s start having a look at the configuration part; in the functional.suite.yml file, just add the REST module and configure it as shown in the following code:

# tests/codeception/functional.suite.yml


      - Filesystem
      - Yii2
      - REST
      - testscodeception_supportFixtureHelper
            configFile: 'codeception/config/functional.php'
            url: 'http://basic-dev.yii2.sandbox'
            url: 'http://basic-dev.yii2.sandbox/v1/'

The last line is quite important, as we will end up making calls by specifying only our endpoint without the need of naming the module base path. Clearly things need to be adjusted accordingly in case you have more than one REST endpoint you need to test.

Recommended :  Complete Guide to CRUD actions in yii framework From scratch

Now, once again we need to run codecept build in order to get everything ready before starting to run our tests. This command, as already seen, will take all the module’s methods and merge them into our actor’s class (which in this case is FunctionalTester).

Let’s generate our new test file with the following commands:

$ cd tests/
$ ../vendor/bin/codecept generate:cept functional UserAPICept
Test was created in UserAPICept.php

Now that we have the file, we can start implementing our tests:

// tests/codeception/functional/UserAPICept.php

$I = new FunctionalTester($scenario);
$I->wantTo('test the user REST API');

We start the file with the initialization of the FunctionalTester and the definition of the scope of our test.

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest