ExpectException 未检测到异常

Tom*_*mov 1 yii2 codeception

我正在尝试测试数据库记录检索。我的测试看起来像:

use yii\db\Exception;

class UserTest extends Unit
{
    protected $tester;
    private $_user;

    public function _before()
    {
        $this->_user = new User();
    }

    public function testRetrievingFALSE()
    {
       $this->expectException(Exception::class, function(){
          $this->_user->retrieveRecords();
       });
    }
}
Run Code Online (Sandbox Code Playgroud)

expectException()文档中看到了该方法。我的模型方法如下所示:

public function retrieveRecords()
{
    $out = ArrayHelper::map(User::find()->all(), 'id', 'username');
    if($out)
        return $out;
    else
        throw new Exception('No records', 'Still no records in db');
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下我做错了什么?

In terminal:
Frontend\tests.unit Tests (1) ------------------------------------------------------------------------------------------
x UserTest: Retrieving false (0.02s)
------------------------------------------------------------------------------------------------------------------------


Time: 532 ms, Memory: 10.00MB

There was 1 failure:

---------
1) UserTest: Retrieving false
 Test  tests\unit\models\UserTest.php:testRetrievingFALSE
Failed asserting that exception of type "yii\db\Exception" is thrown.

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
Run Code Online (Sandbox Code Playgroud)

rob*_*006 5

您没有使用您所指的相同方法。您应该在参与者实例上使用它,而不是在单元测试类本身上。所以要么:

$this->tester->expectException(Exception::class, function(){
    $this->_user->retrieveRecords();
});
Run Code Online (Sandbox Code Playgroud)

或者在验收测试中:

public function testRetrievingFALSE(AcceptanceTester $I) {
    $I->expectException(Exception::class, function(){
        $this->_user->retrieveRecords();
    });
}
Run Code Online (Sandbox Code Playgroud)

如果您在测试类中调用它$this,将使用 PHPUnit 中的方法,其工作方式有所不同:

public function testRetrievingFALSE() {
    $this->expectException(Exception::class);
    $this->_user->retrieveRecords();
}
Run Code Online (Sandbox Code Playgroud)

请参阅PHPUnit 文档中的更多示例。