In this article, we will see how to test a function that throws an exception
when condition meets.
In our previous examples, we have created a calculator
class with functionalities addition and subtraction. In this example, we will add division and will be tested using PHPUnit to check whether the function can throw exception when division by zero is occurred.
1. Add the method division
to the class Calculator
<?php class Calculator{ public function sum($n1, $n2){ return $n1 + $n2; } public function subtract($n1, $n2){ return $n1 - $n2; } public function divide($n1, $n2){ if($n2 == 0) throw new InvalidArgumentException('Division by zero.'); return $n1/$n2; } }
2. Add PHPUnit test
for the division function
This test will test, whether the division will throw and exception or not when division by zero occurs. If the function throws exception, then the test iss success. Other wise, test is failed.
<?php use PHPUnit\Framework\TestCase; class CalculatorTest extends TestCase { public function testIsSumCorrect(){ $calc = new Calculator(); $result = $calc->sum(1,2.5); $expected = 3.5; $this->assertSame($expected,$result); } /** * @dataProvider subtractionProvider */ public function testIsSubtractionCorrect($n1, $n2, $expected){ $calc = new Calculator(); $result = $calc->subtract($n1,$n2); $this->assertSame($expected,$result); } /** * @expectedException InvalidArgumentException */ public function testDivisionByZeroThrowsException(){ $calc = new Calculator(); $result = $calc->divide(1,0); } public function subtractionProvider(){ return [ "data1"=> [ 1 , 1 , 0], "data2"=> [ -1 , 1 , -2], "data3"=> [ 5 , 1 , 4], "data4"=> [ 1 , 0.25 , 0.75] ]; } }
3. Running the test
We can run the test by executing the given below command at the root of the project
$./vendor/bin/phpunit --testdox tests/CalculatorTest.php
On executing the test, PHPUnit will display the test result as given below :
Comments on this post