jeudi 15 septembre 2016

CakePHP unit tests only work once, then I have to reset database

I'm trying to get my team started making some unit tests for our application. The application is built on CakePHP.

To get started, I am building tests for our users table. I have the following Fixture to create a user for me to test against:

namespace App\Test\Fixture;

use Cake\TestSuite\Fixture\TestFixture;

class UsersFixture extends TestFixture
{
      public $connection = 'test';

      public $import = ['table' => 'users'];

      public $records = [
          [
              'username' => 'TestPass',
              'password' => '',
              'email' => 'TestPass@example.com',
              'status' => 'active',
              'created' => '2015-11-04 12:00:00',
              'last_logindate' => null,
              'registration_country' => 'AU',
              'system_user' => 0
          ]
      ];
}

I also have a TestCase for the table:

namespace App\Test\TestCase\Model\Table;

use App\Model\Table\UsersTable;
use Cake\ORM\TableRegistry;
use Cake\TestSuite\TestCase;

/**
 * App\Model\Table\UsersTable Test Case
 */
class UsersTableTest extends TestCase
{

    /**
     * Fixtures
     *
     * @var array
     */
    public $fixtures = [
        'app.Users'
    ];

    /**
     * setUp method
     *
     * @return void
     */
    public function setUp()
    {
        parent::setUp();
        $config = TableRegistry::exists('Users') ? [] : ['className' => 'App\Model\Table\UsersTable'];
        $this->Users = TableRegistry::get('Users', $config);
    }

    /**
     * tearDown method
     *
     * @return void
     */
    public function tearDown()
    {
        unset($this->Users);

        parent::tearDown();
    }
    // ...
}

The first time I run this test it works perfectly. If I try to run it again then I get the following error:

PHPUnit 4.8.27 by Sebastian Bergmann and contributors.

Warning Error: Fixture creation for "users" failed "SQLSTATE[42000]: Syntax error or access violation: 1101 BLOB/TEXT column 'status' can't have a default value" in [/path-to-app/vendor/cakephp/cakephp/src/TestSuite/Fixture/TestFixture.php, line 232]

Exception: Unable to insert fixtures for "App\Test\TestCase\Model\Table\UsersTableTest" test case. SQLSTATE[42S02]: Base table or view not found: 1146 Table 'carebook_test.users' doesn't exist in [/path-to-app/vendor/cakephp/cakephp/src/TestSuite/Fixture/FixtureManager.php, line 253]

The only way for me to get rid of this error seems to be to DROP my database, recreate it and then run my migrations again. After that the test will run successfully another time, before breaking once more.

What am I doing wrong?

Aucun commentaire:

Enregistrer un commentaire