【问题标题】:How to unit test Exceptions with PHPUnit?如何使用 PHPUnit 对异常进行单元测试?
【发布时间】:2011-06-06 12:26:40
【问题描述】:

我不知道如何使用 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 测试:

<?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@ffff.es<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.');  
        }



    }
}
?>

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

1) ScrapTest::testGetPhone
Expected exception Exception

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

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

你能给我一些线索吗?

最好的问候,

【问题讨论】:

标签: php exception-handling phpunit


【解决方案1】:

你做的太多了。

任一使用:@expectedException 异常

OR:try / catch / $this->fail

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

在我看来,第一种方法更简洁,因为它只有 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-&gt;setExpectedException('ExceptionTypeGoesHere'),以及上面列出的两个。我认为这是最干净的方法。
  • 没错。查看dotnetCarpenter's comment 以获取更新的指南。
【解决方案2】:

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

$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-&gt;fail(); 语句将/必须仅在没有引发异常时调用。因此,这个测试用例失败了,因为它应该测试一开始没有抛出的异常。

【讨论】:

  • 至少从 phpunit 6.1 开始,这不再起作用了。 在测试异常时应尽可能具体。测试过于通用的类可能会导致不良的副作用。因此,不再允许使用 @expectedException 或 setExpectedException() 测试 Exception 类。 phpunit.de/manual/current/en/…
  • 在 PHPunit 6+ 中我们需要使用公共函数 testGetPhone() { $this->expectException(\InvalidArgumentException::class);一些代码在这里导致异常}
  • 像魅力一样工作
猜你喜欢
  • 2023-03-06
  • 2013-09-13
  • 1970-01-01
  • 1970-01-01
  • 2019-07-12
  • 2012-02-26
  • 2013-09-22
  • 2014-12-25
  • 2012-03-26
相关资源
最近更新 更多