我想测试我的函数是否拒绝所有非正整数。它抛出 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?
最佳答案
/**
* @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)
);
}
关于php - 如何测试每一行都抛出相同的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16036128/