Search code examples
phpunitcodeception

Using dataProvider in Codeception 2.3.*


Unit tests were written with native PHPUnit, and then we need to cover code with acceptance and functional tests. So tests were modificated for using with Codeception. And all is working, except one thing - Codeception dont understand native PHPUnit dataProviders. I tried @examples and extensions by edno, but it didnt work. Have you any ideas?


Solution

  • dataproviders works a little bit different in codeception, but very well too.

    1. add a private/protected method in your Cest Object (for example, I have an API endpoint that excepts too versions of authentication:

      /**
       * @return array
       */
      protected function tokenProvider()
      {
          return [
              ['name' => "x-client-token", 'value' => 'clientToken'],
              ['name' => "x-api-key", 'value' => 'apikey'],
          ];
      }
      
    2. Add an annotation in front of your test called @dataprovider following the name of the protected method from step [1.] and add a Codeception Example as method parameter. (Namespace Codeception\Example)

      /**
       * @dataprovider tokenProvider
       */
      public function getArticleList(AcceptanceTester $I, Example $token)
      

    Now, the test will call n-times, depending on the number of examples in your array in step [1.]

    Edit/Update:

    To be complete: there is another method for data providers. You can add @example annotation in the doc block so the data is directly injected into the Example object. The annotation can be json, php array syntax or just key value pairs described here: https://codeception.com/docs/07-AdvancedUsage#Example-Annotation

        /*
         * @example {"name": "x-client-token", "value": "clientToken"}
         * @example {"name": "x-api-key", "value": "apikey"}
         */
        public function getArticleList(AcceptanceTester $I, Example $token)
        { 
           // ... 
        }