datasource configuration “default” was not found in CakePHP 3

ε祈祈猫儿з 提交于 2019-12-08 05:42:06

问题


I'm using CakePHP e PHPUnit to execute tests but when I execute a TestCase this error is prompted for every test method:

1) App\Test\TestCase\Model\Table\UsersTableTest::testInitialize Cake\Datasource\Exception\MissingDatasourceConfigException: The datasource configuration "default" was not found.

'Datasources' => [
    'default' => [
        'className' => 'Cake\Database\Connection',
        'driver' => 'Cake\Database\Driver\Mysql',
        'persistent' => false,
        'host' => 'localhost',
        /**
         * CakePHP will use the default DB port based on the driver selected
         * MySQL on MAMP uses port 8889, MAMP users will want to uncomment
         * the following line and set the port accordingly
         */
        //'port' => 'nonstandard_port_number',
        'username' => 'dbusername',
        'password' => 'dbpass',
        'database' => 'dbname',
        'encoding' => 'utf8',
        'timezone' => 'UTC',
        'cacheMetadata' => true,

        /**
         * Set identifier quoting to true if you are using reserved words or
         * special characters in your table or column names. Enabling this
         * setting will result in queries built using the Query Builder having
         * identifiers quoted when creating SQL. It should be noted that this
         * decreases performance because each query needs to be traversed and
         * manipulated before being executed.
         */
        'quoteIdentifiers' => false,

        /**
         * During development, if using MySQL < 5.6, uncommenting the
         * following line could boost the speed at which schema metadata is
         * fetched from the database. It can also be set directly with the
         * mysql configuration directive 'innodb_stats_on_metadata = 0'
         * which is the recommended value in production environments
         */
        //'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'],
    ],
    /**
     * The test connection is used during the test suite.
     */
    'test' => [
        'className' => 'Cake\Database\Connection',
        'driver' => 'Cake\Database\Driver\Mysql',
        'persistent' => false,
        'host' => 'localhost',
        //'port' => 'nonstandard_port_number',
        'username' => 'dbusername',
        'password' => 'dbpass',
        'database' => 'dbnametest',
        'encoding' => 'utf8',
        'timezone' => 'UTC',
        'cacheMetadata' => true,
        'quoteIdentifiers' => false,
        //'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'],
    ],
],

The TestSuite:

<?php
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',
        'app.user_types',
        'app.bookings',
        'app.stores'
    ];

    /**
     * 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();
    }

    /**
     * Test initialize method
     *
     * @return void
     */
    public function testInitialize()
    {
        $this->markTestIncomplete('Not implemented yet.');
    }

    /**
     * Test validationDefault method
     *
     * @return void
     */
    // Método que deverá testar o método "validationDefault()" de "UsersTable",
    // mas como e quando este método será chamado?
    // A ferramenta seleciona o método a ser executado
    public function testValidationDefault()
    {
        $this->markTestIncomplete('Not implemented yet.');
    }

    /**
     * Test buildRules method
     *
     * @return void
     */
    public function testBuildRules()
    {
        $this->markTestIncomplete('Not implemented yet.');
    }

    public function testFindUserById(){
        $query = $this->Users->find('userById', [
            'conditions' => ['Users.id' => 900000],
            'fields' => ['Users.id', 'Users.email', 'Users.password',
                'Users.username', 'Users.user_type_id', 'Users.created',
                'Users.modified']
        ]);
        $this->assertInstanceOf('Cake\ORM\Query', $query);
        $result = $query->hydrate(false)->toArray();

        $expected = [
            [
                'id' => 900000,
                'email' => 'usuariocomum1@gmail.com',
                'password' => 'usuariocomum1senha',
                'username' => 'usuariocomum1username',
                'user_type_id' => 900000,
                'created' => '2015-07-17 18:46:47',
                'modified' => '2015-07-17 18:46:47'
            ]
        ];

        $this->assertEquals($expected, $result);
    }
}

But the datasource "default" and "test" it's OK, the site works fine.

Full command line:

c:\xampp\htdocs\PROJETOS\Shopping\vendor\bin>phpunit "C:/xampp/htdocs/PROJETOS/S
hopping/tests/TestCase/Model/Table/UsersTableTest.php"
PHPUnit 4.8.6 by Sebastian Bergmann and contributors.

EEEE

Time: 3.85 seconds, Memory: 3.75Mb

There were 4 errors:

1) App\Test\TestCase\Model\Table\UsersTableTest::testInitialize
Cake\Datasource\Exception\MissingDatasourceConfigException: The datasource confi
guration "default" was not found.

C:\xampp\htdocs\PROJETOS\Shopping\vendor\cakephp\cakephp\src\Datasource\Connecti
onManager.php:188
C:\xampp\htdocs\PROJETOS\Shopping\vendor\cakephp\cakephp\src\ORM\TableRegistry.p
hp:192
C:\xampp\htdocs\PROJETOS\Shopping\tests\TestCase\Model\Table\UsersTableTest.php:
35

2) App\Test\TestCase\Model\Table\UsersTableTest::testValidationDefault
Cake\Datasource\Exception\MissingDatasourceConfigException: The datasource confi
guration "default" was not found.

C:\xampp\htdocs\PROJETOS\Shopping\vendor\cakephp\cakephp\src\Datasource\Connecti
onManager.php:188
C:\xampp\htdocs\PROJETOS\Shopping\vendor\cakephp\cakephp\src\ORM\TableRegistry.p
hp:192
C:\xampp\htdocs\PROJETOS\Shopping\tests\TestCase\Model\Table\UsersTableTest.php:
35

3) App\Test\TestCase\Model\Table\UsersTableTest::testBuildRules
Cake\Datasource\Exception\MissingDatasourceConfigException: The datasource confi
guration "default" was not found.

C:\xampp\htdocs\PROJETOS\Shopping\vendor\cakephp\cakephp\src\Datasource\Connecti
onManager.php:188
C:\xampp\htdocs\PROJETOS\Shopping\vendor\cakephp\cakephp\src\ORM\TableRegistry.p
hp:192
C:\xampp\htdocs\PROJETOS\Shopping\tests\TestCase\Model\Table\UsersTableTest.php:
35

4) App\Test\TestCase\Model\Table\UsersTableTest::testFindUserById
Cake\Datasource\Exception\MissingDatasourceConfigException: The datasource confi
guration "default" was not found.

C:\xampp\htdocs\PROJETOS\Shopping\vendor\cakephp\cakephp\src\Datasource\Connecti
onManager.php:188
C:\xampp\htdocs\PROJETOS\Shopping\vendor\cakephp\cakephp\src\ORM\TableRegistry.p
hp:192
C:\xampp\htdocs\PROJETOS\Shopping\tests\TestCase\Model\Table\UsersTableTest.php:
35

FAILURES!
Tests: 4, Assertions: 0, Errors: 4.

I test now (01/09/2015 (1st september) - 09:56) and doesn't error in [projectName]/logs/cli-error and [projectName]/logs/error with this date.

NOTE: CakePHP version 3.0.11


回答1:


You're not running the test suite correctly, what you are doing there will cause PHPUnit to not pick up the test suite configuration that lives in your applications root (phpunit.xml.dist)

As per the docs, you should run the suite from your applications root directory

[...]

By using phpunit you can run your application tests. To run your application’s tests you can simply run:

// composer installs
$ vendor/bin/phpunit

// phar file
php phpunit.phar

From your application’s root directory.

[...]

* emphasis mine

Cookbook > Testing > Running Tests

So you should CD into the Shopping directoy, and run PHPUnit using a relative path like

cd c:\xampp\htdocs\PROJETOS\Shopping
vendor\bin\phpunit tests\TestCase\Model\Table\UsersTableTest.php



回答2:


First set up a test database and then add this to your app.php file:

 'test' => [
            'className' => 'Cake\Database\Connection',
            'driver' => 'Cake\Database\Driver\Mysql',
            'persistent' => false,
            'host' => 'YOUR TEST HOST',
            'username' => 'USERNAME',
            'password' => 'PASSWORD',
            'database' => 'YOUR TEST DB',
            'encoding' => 'utf8',
            'timezone' => 'UTC',
            'cacheMetadata' => true,
            'quoteIdentifiers' => false,
            //'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'],
        ],


来源:https://stackoverflow.com/questions/32330878/datasource-configuration-default-was-not-found-in-cakephp-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!