用phpunit测试异常

时间:2015-07-27 12:10:29

标签: php phpunit

我正在尝试测试一个函数,当我知道错误时我会被抛出。该函数如下所示:

function testSetAdsData_dataIsNull(){
    $dataArr = null;
    $fixture = new AdGroup();

        try{
            $fixture->setAdsData($dataArr);
        } catch (Exception $e){
            $this->assertEquals($e->getCode(), 2);
        }

    $this->assertEmpty($fixture->ads);
    $this->assertEmpty($fixture->adIds);
}

现在我正在尝试使用phpunit异常断言方法来替换try catch部分,但我无法弄清楚如何做到这一点。 我做了很多阅读,包括这篇文章PHPUnit assert that an exception was thrown?,但我真的不明白它是如何实施的。

我试过这样的事情:

/**
 * @expectedException dataIsNull

 */

function testSetAdsData_dataIsNull(){
    $dataArr = null;
    $fixture = new AdGroup();

    $this->setExpectedException('dataIsNull');
    $fixture->setAdsData($dataArr);
    $this->assertEmpty($fixture->ads);
    $this->assertEmpty($fixture->adIds);
}

but obviously it didn't work  and i got this error:
1) adGroupTest::testSetAdsData_dataIsNull
ReflectionException: Class dataIsNull does not exist

我做错了什么以及如果抛出异常pz怎么断言?

1 个答案:

答案 0 :(得分:1)

我通常会在这种情况下使用@expectedException注释。见all exception-related annotations here

/**
 * @expectedException \Exception
 * @expectedExceptionCode 2
 */
function testSetAdsData_dataIsNull()
{
    $dataArr = null;
    $fixture = new AdGroup();

    $fixture->setAdsData($dataArr);
}

检查$fixture->ads是否真的为空并没有在这里真正添加,你可以在实际触发异常的调用之前添加这些断言:

$this->assertNull($fixture->ads);
$fixture->setAdsData($dataArr);//throws exception

你是单位测试。此测试有一个明确的目的:它确保在给定情况下抛出异常。如果是,那就是测试结束的地方。

但是,如果你想保留这些assertEmpty电话,你可以这样做:

try {
    $fixture->setAdsData($dataArr);
    $e = null;
} cathc (Exception $e) {}
$this->assertEmpty($fixture->ads);
$this->assertEmpty($fixture->adIds);
if (!$e instanceof \Exception) {
    //if the exception is not thát important:
    $this->markTestIncomplete('No Exception thrown');
    //do other stuff here... possibly
    $this->fail('The exception was not thrown');
}
throw $e;//throw exception a bit later

另一种方法是手动调用$this->setExpectedException as explained here。由于我们似乎不知道/关心异常消息的样子,我将使用setExpectedExceptionRegExp方法:

$fixture = new AdGroup();
$this->setExpectedExceptionRegExp(
    //exception class, message regex, exception code
    'Exception', '/.*/'. 2
);
$fixture->setAdsData(null);//passing null seems to be what you're doing anyway