2015-01-27 41 views
-1

我有以下代碼來測試類構造函數是否會觸發異常但PHPUnit測試失敗。我想弄清楚我做錯了什麼。測試PHPUnit測試「__construct()必須是..的一個實例」不能識別異常

/** @test */ 
public function should_require_instance_of_uuid() 
{ 
    $this->setExpectedException('Exception'); 
    $id = new BusinessPartnerId; 
} 

PHPUnit的提供了以下錯誤: 有1個錯誤: 1)測試\域\型號\ COMMON \業務夥伴\ BusinessPartnerIdTest :: should_require_instance_of_uuid 參數1傳遞給域\型號\ COMMON \業務夥伴\ BusinessPartnerId :: __ construct()必須是Rhumsaa \ Uuid \ Uuid的一個實例,沒有給出,在第14行的tests/Comain/Model/Common/BusinessPartner/BusinesPartnerIdTest.php中調用,並且定義爲

Domain/Model/Common/BusinessPartner /BusinessPartnerId.php:20 tests/Domain/Model/Common/BusinessPartner/BusinesPartnerIdTest.php:14

我不知道爲什麼這個測試沒有通過?我也曾嘗試: $this->setExpectedException('InvalidArgumentException');

回答

1

您的測試應該長相:

如果你有類:

class Stack 
{ 
    public function __construct(\Model $model) 
    { 
    } 
} 

然後測試:

/** 
* @test 
*/ 
public function shouldCheckInstance() 
{ 
    try { 
     new Stack(null); 
    } catch(\Exception $e) { 
     $this->assertContains('must be an instance of Model', $e->getMessage()); 
    } 
} 
+0

這個工作!謝謝。 –

0

雖然我還沒有與當前工作PHPUnit,舊版本不允許你捕獲基本的異常,但會捕獲你自己的擴展到Exception類。另外,這個異常可能是命名空間的,所以它是\ Exception,而不僅僅是Exception。

我還在文檔塊中使用了@expectedException來指示我期待的異常。

/** 
* @test 
* @expectedException \MyNamespace\MyException 
*/ 
public function shouldCheckInstance() 
{ 
    new MyClass(): 
} 

/** 
* @test 
*/ 
public function shouldCheckInstance() 
{ 
    $this->setExpectedException('\MyNamespace\MyException'); 
    new MyClass(): 
}