expectException 没有检测到异常

expectException doesn't detect the exception

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

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

我在documentation中看到了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');
}

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

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.

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

$this->tester->expectException(Exception::class, function(){
    $this->_user->retrieveRecords();
});

或在验收测试中:

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

如果您在测试 class 中的 $this 上调用它,将使用来自 PHPUnit 的方法,其工作方式不同:

public function testRetrievingFALSE() {
    $this->expectException(Exception::class);
    $this->_user->retrieveRecords();
}

PHPUnit documentation 中查看更多示例。