2013-04-16 44 views
2

我想測試我的函數拒絕所有非正整數。它引發一個InvalidArgumentException。我寫了這樣的測試:我如何測試每條線都拋出相同的異常?

/** 
* @test 
* @expectedException InvalidArgumentException 
*/ 
public function testXThrowsException() 
{ 
    $this->parser->x(1.5); 
    $this->parser->x('2'); 
    $this->parser->x(1000E-1); 
    $this->parser->x(+100); 
} 

我的測試總是通過,因爲第一個引發異常。其他人沒有得到正確的測試。我可以將$this->parser->x(1);添加到我的代碼中,它仍然會通過。

我應該怎麼做才能斷言所有這些函數調用都會引發InvalidArgumentException?

回答

2
/** 
* @test 
* @expectedException InvalidArgumentException 
* 
* @dataProvider foo 
*/ 
public function testXThrowsException($value) 
{ 
    $this->parser->x($value); 
} 

/** 
* Test data 
* Returns array of arrays, each inner array is used in 
* a call_user_func_array (or similar) construction 
*/ 
public function foo() 
{ 
    return array(
     array(1.5), 
     array('2'), 
     array(1000E-1), 
     array(+100) 
    ); 
} 
+0

非常好,謝謝! – Sherlock

1

一種解決方案是使用這樣的:

/** 
* @test 
*/ 
public function testXThrowsException() 
{ 
    try { 
     $this->parser->x(1.5); 
     $this->fail('message'); 
    } catch (InvalidArgumentException $e) {} 
    try { 
     $this->parser->x('2'); 
     $this->fail('message'); 
    } catch (InvalidArgumentException $e) {} 
    try { 
     $this->parser->x(1000E-1); 
     $this->fail('message'); 
    } catch (InvalidArgumentException $e) {} 
    try { 
     $this->parser->x(+100); 
     $this->fail('message'); 
    } catch (InvalidArgumentException $e) {} 

} 

現在,您可以測試自己的每一行。無論何時方法x()確實不是引發異常,測試失敗使用fail()

+0

智能解決方案,謝謝! – Sherlock

0

如果你有很多的負值的,你也可以把它們放在一個數組和循環陣列上用下面的代碼(未經測試):

foreach($wrongValueArray as $failtyValue) { 
    try { $this->parser->x($failtyValue); 
     this->fail($failtyValue . ' was correct while it should not'); 
    } catch (InvalidArgumentException $e) {} 
} 

這是一個有點短