CakePHP 3.x 单元测试 "Base table or view not found"

CakePHP 3.x UnitTest "Base table or view not found"

我在 CakePHP 3.2 的单元测试中收到一条错误消息,官方文档在这里不再对我有帮助。我认为该错误与我尝试使用的 SQL-Joins 有关。

错误消息如下:

`1) App\Test\TestCase\Controller\GetContentControllerTest::testIndex
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'contentmapper_test.CmDeviceclasses' doesn't exist`

在我的测试类 GetContentControllerTest 中,我加载了我需要的装置,并在开始时创建了我的数据库-Tables:

`public $fixtures = [
        'app.cm_content_options', 
        'app.cm_content_addresses', 
        'app.cm_deviceclasses', 
        'app.cm_properties'
    ];`

setUp()-方法中我加载了Main-Table:

`public function setUp()
 {
    parent::setUp();
    $this->CmContentOptions = TableRegistry::get('CmContentOptions');      
 }`

我的测试方法 testIndex() 看起来像这样:

public function testIndex() 
{
    //find the belonging ContentOption to address data 
    //submitted by the client
    $this->testFindAllByUriAndDeviceclassAndBoxId();   

    assert($this->arrObjContentOptions->count() == 1);        
}

testFindAllByUriAandDeviceclassAndBoxID() 如下图所示(编辑器无法正确打印):

testFindAllByUriAandDeviceclassAndBoxID()

很难描述整个上下文;希望可以理解。

错误恰好发生在图中所示的语句上:

$result = $query->toArray()

我想我只是忘了在 setUp() 方法中添加一些东西或类似的东西。

希望大家帮帮忙

您的连接设置不正确,您混淆了别名和 table 名称。

别名是连接数组的键,table 键应该包含实际的数据库 table 名称,而不是 table class 名称。

鉴于您遵循数据库 table 名称的 CakePHP 命名约定,您的连接设置应该更像这样

[
    'CmDeviceclasses' => [ /* < this is the SQL alias */
        'table' => 'cm_deviceclasses', /* < this is the database table name */
        'type' => 'LEFT',
        'conditions' => [
            'CmDeviceclasses.classname' => $this->deviceclass
        ]
    ],
    'CmContentAddresses' => [
        'table' => 'cm_content_addresses',
        'type' => 'INNER',
        'conditions' => [
            'CmContentAddresses.uri' => $this->uri,
            'CmContentAddresses.boxid' => $this->boxid,
        ]
    ],
],
[
    'CmDeviceclasses.classname' => 'string',
    'CmContentAddresses.uri' => 'string',
    'CmContentAddresses.boxid' => 'string'
]

对于别名,没有遵循 CamelCase 惯例的技术需求,但可以肯定的是,通常坚持这些惯例并没有什么坏处。

ps,如果你正确设置关联,那么应该不需要使用手动连接,你可以只使用 Query::contain()Query::innerJoinWith()Query::matching() .