2017-08-10 38 views
0

在處理其他信息而不是消息或代碼時,對拋出的異常執行任意斷言可能很有用。更好的解決方案對預期異常執行任意斷言?

有沒有更簡單,可讀,或更「PHPUnit的推薦方式」來做到這一點,比下面的例子:

public function testTitleShouldNotAcceptArrayAsValue() 
{ 
    /* Arrange */ 
    $schema = new sch\ObjectSchema(); 


    /* Expect */ 
    $this->expectException(sch\Exception::class); 


    try { 
     /* Act */ 
     $schema->title = []; 
    } catch (sch\Exception $exception) { 
     /* Assert */ 
     $this->assertEquals('title', $exception->getProperty()); 
     $this->assertEquals(
      [ 
       'properties' => [ 
        'title' => [ 
         'type' => 'string' 
        ] 
       ] 
      ], 
      $exception->getRules() 
     ); 
     throw $exception; 
    } 
} 

回答

2

如果你是把更多的信息到異常對象,並想要在測試中證明它正在設置,那麼我會使用try/catch。

IMO,expectException()throw雖然是多餘的。在捕獲結束時,我將通過合格返回函數,並且在catch塊失敗後(使用$this->fail('sch\Exception was not thrown');),因爲沒有發生例外情況,按照計劃。

它會完全顯而易見,它在做 - 而且清晰度在很大程度上比優雅更有用。

相關問題