2011-01-10 88 views
12

我沒有得到如何使用PHPUnit對異常進行單元測試。如何使用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 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.'); 
     } 



    } 
} 
?> 

如果我跑的測試中,我得到了 「失敗」:

1) ScrapTest::testGetPhone 
Expected exception Exception 

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

異常提出了,但我不想在PHPUnit中失敗,如果異常提出,我想要測試OK。

你能給我一些線索嗎?

最好的問候,

+1

[如何使用PHPUnit的setExpectedException()?](http://stackoverflow.com/questions/4646298/how-to-use-phpunits-setexpectedexception) – zerkms 2011-01-10 12:33:28

+0

剛纔幾分鐘前被問到 – Gordon 2011-01-10 12:55:06

回答

29

你做得太多了那裏。

使用:@ExpectedException異常

OR:try/catch語句/ $這個 - >失敗

你正在做的是正確的,現在說「捕獲了異常的方式,然後期待代碼扔另一個!「

第一種方法在我看來是更清潔的,因爲它只對5行(甚至更多)代碼行只有1行,並且不太容易出錯。

/** 
* @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');   

這應該這樣做。

+4

您可以也可以在測試方法的頂部使用`$ this-> setExpectedException('ExceptionTypeGoesHere')`以及上面列出的兩個。我認爲這是最乾淨的方法。 – TeaPow 2013-03-13 15:36:34

12

有兩種方法可以測試拋出的異常,但它取決於您的需求。如果你不關心的內容/異常(即代碼,信息等)的性能,那麼你可以做:

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

另外,如果你需要使用異常屬性斷言(即代碼) ,那麼你可以做的try-catch-失敗:

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

$this->fail(); 

通知的catch塊內的return聲明。 只有在沒有引發異常時纔會調用$this->fail();語句。因此,這個測試用例失敗了,因爲它應該測試不首先拋出的異常。