Reputation: 573
I'm actually trying to understand PHPUNIT and unit testing with PHP.
I have a classic divide methode.
public function divide($firstNumber, $secondNumber){
if( !is_numeric($firstNumber) || !is_numeric($secondNumber) ){
throw new Exception("Not a number") ;
}
if( $secondNumber == 0 ) throw new Exception("Can't divide by zero") ;
return $firstNumber/$secondNumber ;
}
As you can see It can return a Number or Exception. Here is the testDivide code that I used.
/**
* @dataProvider diviserDateProvider
* @covers MyTools::diviser
*/
public function testDivide($firstNumber, $secondNumber, $expected) {
$myToolsClasse = new MyTools();
$this->assertEquals($expected, $myToolsClasse->diviser($firstNumber, $secondNumber));
}
public function diviserDateProvider() {
return array(
array(1, 0, new Exception("Can't divide by zero")),
array(1, 2, 0.5),
array("", "", 0.5)
);
}
As you can see there is a DataProvider with multiple testing values. The problem is I have to Except/Assert an Exception which is the best way to do it ?
Should I use @exceptException and use try catch in my testDivide code ? Thanks for your help have a nice day!
Upvotes: 2
Views: 4743
Reputation: 89
Try this
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Expected Exception Message');
Upvotes: 4
Reputation: 8306
The best practice for testing exceptions with PHPUnit is to use expectException()
in your test method's code.
Upvotes: 3