dimanche 12 mars 2017

PHPUnit Test Exception and AssertEquals

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!

Aucun commentaire:

Enregistrer un commentaire