如何使用PHPUnit对异常进行单元测试?

如何使用PHPUnit对异常进行单元测试?,php,exception-handling,phpunit,Php,Exception Handling,Phpunit,我不知道如何使用PHPUnit对异常进行单元测试 请参见我的方法,例外情况如下: public function getPhone($html, $tag = 'OFF', $indicative, $number_lenght) { // .. code if ($tag <> 'OFF') { $html = $doc[$tag]->text(); // Apanho apenas o texto den

我不知道如何使用PHPUnit对异常进行单元测试

请参见我的方法,例外情况如下:

    public function getPhone($html, $tag = 'OFF', $indicative, $number_lenght) {

        // .. code

        if ($tag <> 'OFF') {

            $html = $doc[$tag]->text(); // Apanho apenas o texto dentro da TAG
                if (empty($html)) {
                    throw new Exception("Nao foi possivel apanhar qualquer texto dentro da TAG, Metodo em causa: getPhone()");
                }               
        }

        // .. code
    }
异常会引发,但我不想在PHPUnit中失败,如果异常引发,我想让测试正常

你能给我一些线索吗


致以最诚挚的问候,

你在那里做得太多了

使用:@expectedException异常

:尝试/catch/$this->失败

您现在的操作方式是“捕获该异常,然后期望代码抛出另一个异常!”

在我看来,第一种方法更简洁,因为它只需要1行代码和5行(甚至更多)代码,而且不太容易出错

/**
* @covers Scrap::getPhone
* @expectedException Exception
*
*/
public function testGetPhone() {

    // Variables1
    $array_static1 = Array(0 => 218559372, 1 => 927555929, 2 => 213456789, 3 => 912345678);
    $phone_list1   = '...';

    // Variables2
    $array_static2 = Array(0 => 'NA');
    $phone_list2   = "";

    // .. more tests

    // Bloco try/catch para confirmar que aqui lança excepção
    $this->scrap->getPhone($phone_list1, 'hr', '351', '9');        

应该这样做。

有两种方法可以测试抛出的异常,但这取决于您的需要。如果您不关心异常的内容/属性(即代码、消息等),则可以执行以下操作:

$this->setExpectedException('MyApp\Exception');
$object->someFailingCodeWithException();
否则,如果需要对断言(即代码)使用异常属性,则可以执行try-catch-fail:

try {
    $object->someFailingCodeWithException();
} catch (MyApp\Exception $e) {
    $this->assertEquals($e->getCode(), 100);
    return;
}

$this->fail();
注意
catch
块中的
return
语句。
$this->fail()语句将/必须仅在未引发异常时调用。因此,这个测试用例失败了,因为它应该测试一开始没有抛出的异常

几分钟前,您还可以在测试方法的顶部使用
$this->setExpectedException('ExceptionTypeGoesher')
,以及上面列出的两种方法。我认为这是最干净的方法。看看更新的指南。至少从phpunit6.1来看,这已经不起作用了。测试异常时,您应该尽可能具体。对过于泛型的类进行测试可能会导致不良的副作用。因此,不再允许使用@expectedException或setExpectedException()测试异常类。在PHPunit 6+中,我们需要使用公共函数testGetPhone(){$this->expectException(\InvalidArgumentException::class);一些代码在这里引起异常}的效果非常好
$this->setExpectedException('MyApp\Exception');
$object->someFailingCodeWithException();
try {
    $object->someFailingCodeWithException();
} catch (MyApp\Exception $e) {
    $this->assertEquals($e->getCode(), 100);
    return;
}

$this->fail();