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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4646822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:50:37  来源:igfitidea点击:

How to unit test Exceptions with PHPUnit?

phpexception-handlingphpunit

提问by André

I'm not getting how to unit test Exceptions with PHPUnit.

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

Please see my method with the Exception:

请参阅我的方法与异常:

    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
    }

And now my PHPUnit Test:

现在我的 PHPUnit 测试:

<?php

require_once '../Scrap.php';

class ScrapTest extends PHPUnit_Framework_TestCase
{

    protected $scrap;

    // Setup function to instantiate de object to $this->scrap
    protected function setUp()
    {
        $this->scrap = new Scrap;
    }

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

        // Variables1
        $array_static1 = Array(0 => 218559372, 1 => 927555929, 2 => 213456789, 3 => 912345678);
        $phone_list1   = '</div>A Front para<br /><br /><br /><br /><br /><br />-Apoio;<br />-Cria??o;<br />-Campanhas;<br />-Promo??es<br /><br /><br />CONDI??ES:<br /><br />Local de Trabalho: Es<br />Folgas: Mistas<br /><br /><br /><br />ordem 500<br /><br /><br /><br />Mínimos:<br /><br />- Conhecimentos;<br />- Ensino ;<br />-INGLêS.<br /><br /><br /><br />Candidaturas: <br />[email protected]<br />218559372 | 927 555 929 | <br />RH<br />Rua C. Sal. 40<br />1000-000 Lisboa<br /><br /><br />+351 21 3456789 | (351) 912345678';

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

        // .. more tests

        // Test Exception, Tag not found
        if (TRUE) {

            // Bloco try/catch para confirmar que aqui lan?a excep??o
            try {            
                    $this->scrap->getPhone($phone_list1, 'hr', '351', '9');        
                }         
            catch (Exception $expected) {
                    return;        
                }         

            $this->fail('An expected exception has not been raised.');  
        }



    }
}
?>

If I run the test I got "Failure":

如果我运行测试,我会得到“失败”:

1) ScrapTest::testGetPhone
Expected exception Exception

FAILURES!
Tests: 1, Assertions: 5, Failures: 1.

The exception raises but I don't want to get failure in the PHPUnit, If the Exception raise, I want to get the test OK.

异常引发但我不想在 PHPUnit 中失败,如果引发异常,我想让测试正常。

Can you give me some clues?

你能给我一些线索吗?

Best Regards,

此致,

回答by edorian

You are doing too much there.

你在那里做得太多了。

Eitheruse: @expectedException Exception

要么使用:@expectedException Exception

OR: try / catch / $this->fail

:尝试/捕获/ $this->fail

The way you are doing it right now says "catch that exception and THEN expect the code to throw another one!"

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

The first way is cleaner in my opinion because it's only 1 line against 5 (or even more) lines of code and it's less error prone.

在我看来,第一种方法更清晰,因为它只有 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');        

That should do it.

应该这样做。

回答by Aldee

There are two ways to test thrown exceptions but it depend on your needs. If you don't care about the content/properties of the exception (i.e. code, message, etc), then you can do:

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

$this->setExpectedException('MyApp\Exception');
$object->someFailingCodeWithException();

Else, if you need to use exception properties for assertion (i.e. code), then you can do the try-catch-fail:

否则,如果您需要使用异常属性进行断言(即代码),那么您可以执行 try-catch-fail:

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

$this->fail();

Notice the returnstatement inside the catchblock. The $this->fail();statement will/must be only called once there is no exception raised. Thus, this test case fails because it should test the exception which is not thrown in the first place.

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