I wrote a simple test for my Yii2 application using Codeception. Instead of using the real MySQL db, I want to use fixtures.
Here is the code:
tests/PersonTest.php:
namespace app\tests\unit\models;
use tests\fixtures;
use app\controllers;
class PersonTest extends \Codeception\Test\Unit
{
protected $tester;
public $appConfig = '@app/config/main.php';
protected function _before(){ }
protected function _after(){ }
public function _fixtures()
{
return [ 'Person' => fixtures\PersonFixture::className() ];
}
public function testUser(){
$person = Person::findOne( [ "id" => 1 ] );
$userId = isset( $person->id ) ? $person->id : false;
$this->assertEquals( 1, $userId );
}
}
tests/fixtures/data/Person.php
return [
'person1' => [
'id' => 1,
'firstname' => 'Foo',
'lastname' => 'Bar',
],
];
tests/fixtures/Person.php
namespace tests\fixtures;
use yii\test\ActiveFixture;
class PersonFixture extends ActiveFixture
{
public $modelClass = 'app\models\Person';
}
When I run the test, I just get the error:
[Error] Class 'tests\fixtures\PersonFixture' not found
I tried 100 different things, but I can not make it work. If this simple example would work for me, I could create real tests.
With Codeception 2.3.8 you can do it like this:
Define your fixture (and have the data file just like you have in your question)
namespace app\tests\fixtures;
class PersonFixture extends \yii\test\ActiveFixture {
public $modelClass = 'app\models\Person';
}
And write your test
namespace app\tests\unit;
class PersonTest extends \Codeception\Test\Unit {
public function _fixtures() {
return [
'persons' => 'app\tests\fixtures\PersonFixture',
];
}
public function testUser() {
$person1 = $this->tester->grabFixture('persons', 'person1');
$this->assertEquals(1, $person1->id);
}
}
That's it.
with codeception 4.0.3 you can run your fixture by following the steps...
create fixtures folder inside test
[fixture folder][1]
[1]: https://i.stack.imgur.com/uK9Cy.png
inside your fixtures/data/book.php
<?php
return [
'book1' => [
'title' => 'lmayert',
'isbn' => 'Ibn-098',
],
'user2' => [
'title' => 'napoleon69',
'isbn' => 'Ibn-042',
],
];
your fixtures/BookFixture be like this:
<?php
namespace app\tests\fixtures;
use yii\test\ActiveFixture;
/**
*
*/
class BookFixture extends ActiveFixture
{
public $modelClass = 'app\models\Book';
}
Now the tests/unit/BookTest be like this
<?php
use app\tests\unit\fixtures\BookFixture;
class BookTest extends \Codeception\Test\Unit
{
/**
* @var \UnitTester
*/
protected $tester;
protected function _before()
{
}
protected function _after()
{
}
public function _fixtures() {
return [
'books' => 'app\tests\fixtures\BookFixture',
];
}
// tests
public function testBook()
{
$book1 = $this->tester->grabFixture('books','book1');
$this->assertEquals(1,$book1->id);
}
}
I hope this will help
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With