3

I am setting up Codeception for Api testing.

I have a Cest class, say...

class ZooCest {
    public function addingALionToZoo(ApiTester $I)
    {
        $I->sendPost('zoo/add_animal', ['animal_id' => $animalId]);
    }
}

The question is, where and how do I set up the data to test my api.

Following the previous example, I could do this:

class ZooCest {
    public function addingALionToZoo(ApiTester $I)
    {
        $lion = new Animal('lion');
        $lion->save();

        $I->sendPost('zoo/add_animal', ['animal_id' => $lion->getId()]);
    }
}

But this gets messy when business logic is complicated.

I could have a factorizer in the support folder, so I could so this:

class ZooCest {
    public function addingALionToZoo(ApiTester $I)
    {
        $lion = DataFactory::create('lion');

        $I->sendPost('zoo/add_animal', ['animal_id' => $lion->getId()]);
    }
}

But that can grow a lot, becoming more and more complex as time passes, reaching a point in which we might even need testing for that logic! (yes, it's a joke)

Thanks.

Hector Ordonez
  • 1,044
  • 1
  • 12
  • 20

1 Answers1

0

I don't think there's a "best place" for that since it all depends on your project and your tests, so this is more like a theoretic answer.

If you have (or may have) that many logic, I would probably create a new directory just for this kind of stuff where you can create as many classes as it makes sense to you. For instance:

- app
  - TestsData
    - Zoo.php
    - Oceanarium.php
    - Theatre.php
    - Shop.php

Of you could go even further and devide it like:

- app
  - TestsData
    - Zoo
      - Lion.php
      - Monkey.php
    - Oceanarium
      - Shark.php

Either way, you could create a few methods in each class just to "seed" the database with the information you want (demo for TestsData/Zoo/Lion.php).

<?php

use Animal;

class Lion 
{
    public static function add() {
        $lion = new Animal('lion');
        $lion->save();

        return $lion;
    }
}

Then, in your tests use:

class ZooCest {
    public function addingALionToZoo(ApiTester $I)
    {
        $I->sendPost('zoo/add_animal', ['animal_id' => Lion::add()]);
    }
}
Luís Cruz
  • 14,780
  • 16
  • 68
  • 100