2017-04-11 52 views
1

我使用Codeception爲我的Yii2應用程序寫了一個簡單的測試。而不是使用真正的MySQL數據庫,我想使用燈具。Yii2 + Codeception:如何使用燈具?

下面是代碼:

測試/ 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); 
    } 
} 

測試/裝置/數據/ Person.php

return [ 
    'person1' => [ 
     'id'   => 1, 
     'firstname'  => 'Foo', 
     'lastname'  => 'Bar', 

    ], 
]; 

測試/夾具/Person.php

namespace tests\fixtures; 

use yii\test\ActiveFixture; 

class PersonFixture extends ActiveFixture 
{ 
    public $modelClass = 'app\models\Person'; 
} 

當我運行測試,我剛剛得到的錯誤:

[錯誤]類 '測試\燈具\ PersonFixture' 未找到

我試過100個不同的東西,但我可以沒有使它工作。如果這個簡單的例子適合我,我可以創建真正的測試。

回答

-1

您必須使用yii2-codeception擴展名,它可以自動爲您加載燈具。

安裝完畢後,您可以使用yii\codeception\DbTestCase類,PersonTest應該擴展它。

人員夾具應具有名稱空間如下:app\tests\fixtures

+3

請注意,yii2-codeception擴展已棄用:https://github.com/yiisoft/yii2-codeception – yesnik

0

隨着Codeception 2.3.8,你可以做這樣的:

定義您的燈具(並且有就像你在你的問題中的數據文件)

namespace app\tests\fixtures; 

class PersonFixture extends \yii\test\ActiveFixture { 

    public $modelClass = 'app\models\Person'; 

} 

而且編寫測試

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); 
    } 

} 

就是這樣。