我正在尝试测试检索的数据库记录。我的测试如下:
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.
答案 0 :(得分:2)
您使用的不是您所指的相同方法。您应该在actor实例上使用它,而不是在单元测试类本身上使用它。所以:
$this->tester->expectException(Exception::class, function(){
$this->_user->retrieveRecords();
});
或在验收测试中:
public function testRetrievingFALSE(AcceptanceTester $I) {
$I->expectException(Exception::class, function(){
$this->_user->retrieveRecords();
});
}
如果您在测试类的$this
上调用它,则将使用PHPUnit的方法,其工作方式有所不同:
public function testRetrievingFALSE() {
$this->expectException(Exception::class);
$this->_user->retrieveRecords();
}
在PHPUnit documentation中查看更多示例。