Where and how to set up data for testing Apache Codeception (Cests)
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 it gets messy when the business logic is complex.
I could have a factorizer in the support folder, so I could like this:
class ZooCest {
public function addingALionToZoo(ApiTester $I)
{
$lion = DataFactory::create('lion');
$I->sendPost('zoo/add_animal', ['animal_id' => $lion->getId()]);
}
}
But it can grow a lot, becoming more and more complex over time, reaching the point where we might need testing for this logic! (yes, that's a joke)
Thank.
source to share
I don't think there is a "best place" for this, because it all depends on your project and your tests, so this sounds more like a theoretical answer.
If you have (or might have) a lot of logic, I would probably create a new directory for just this kind of stuff, where you can create as many classes as makes sense to you. For example:
- app
- TestsData
- Zoo.php
- Oceanarium.php
- Theatre.php
- Shop.php
You can go even further and split it like this:
- app
- TestsData
- Zoo
- Lion.php
- Monkey.php
- Oceanarium
- Shark.php
In any case, you can create multiple methods in each class by simply "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()]);
}
}
source to share