Codeception测试采用“默认”数据源,而不是CakePHP 3中的“测试”

时间:2018-11-22 14:22:22

标签: php unit-testing cakephp-3.0 codeception

我能够通过Codeception运行UnitTests,但是当涉及到数据库并修复其令人困惑时...

我的codeception.dist.yml

namespace: App\TestSuite\Codeception
paths:
    tests: tests
    output: tmp/tests
    data: tests/Fixture
    support: src/TestSuite/Codeception
    envs: tests/Envs
settings:
    bootstrap: bootstrap.php
    colors: true
    memory_limit: 1024M
actor_suffix: Tester
extensions:
    enabled:
        - Codeception\Extension\RunFailed
modules:
    config:
        Db:
            dsn: 'mysql:host=%DB_HOST_TEST%;dbname=%DB_NAME_TEST%'
            user: '%DB_USER_TEST%'
            password: '%DB_PASSWORD_TEST%'
            dump: tests/_data/dump.sql
            cleanup: true # reload dump between tests
            populate: true # load dump before all tests
            reconnect: true
    enabled:
        - Db
params:
    - env

在运行我的测试时,dump.sql被导入到测试数据库中。没有插入灯具...

然后在测试中,我做这样的事情(缩短):

<?php
namespace App\Test\Unit\Model\Behavior;

use App\Model\Behavior\HashableBehavior;
use App\Model\Entity\User;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
use Cake\TestSuite\TestCase;

/**
 * App\Model\Behavior\HashableBehavior Test Case
 */
class HashableBehaviorTest extends \Codeception\Test\Unit
{
/**
 * Test subject
 *
 * @var \App\Model\Behavior\HashableBehavior
 */
public $Hashable;

public $fixtures = [
    'app.Users',
    'app.mandators'
];

/**
 * Test subject
 *
 * @var \App\Model\Table\UsersTable
 */
public $UsersTable;

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

    $this->Hashable = new HashableBehavior($this->UsersTable);
}

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

    parent::tearDown();
}

/**
 * Test beforeSave method
 *
 * @return void
 * @throws \Exception
 */
public function testBeforeSave()
{
    $user = $this->UsersTable->get(1);
    ...

}

这给了我默认数据库而不是测试数据库的第一条记录。我不知道这里缺少什么...很高兴能提供帮助!

1 个答案:

答案 0 :(得分:0)

再次检查所有代码后,我在tests / bootstrap.php中找到以下行:

if (getenv('db_dsn')) {
    putenv('DATABASE_URL=' . getenv('db_dsn'));
    putenv('DATABASE_TEST_URL=' . getenv('db_dsn'));
}

即使我找不到使用变量DATABASE_TEST_URL的位置,也可以将其添加到我的.env文件中来解决该问题:

export db_dsn="mysql://db_usr:db_password@db_host/db_name?encoding=utf8&timezone=UTC&cacheMetadata=true&quoteIdentifiers=false&persistent=false"

变量DATABASE_TEST_URL在.env中,但对此没有任何影响。。。我认为cakePHP和Codeception整合得不好。

仍然没有将我的装置加载到UnitTests中(类MyTest扩展了\ Codeception \ Test \ Unit)-但是问题得以解决。

[更新]夹具加载已修复。我必须手动注入FixtureManager并将fxtures加载到setUp函数中。