When testing for exceptions with PHPUnit, what is the best way to require that every statement or assertion must throw an exception in order for the test to pass?
I basically want to do something like this:
public function testExceptions() { $this->setExpectedException('Exception'); foo(-1); //throws exception foo(1); //does not throw exception } //Test will fail because foo(1) did not throw an exception
I've come up with the following, which does the job, but is quite ugly IMO.
public function testExceptions() { try { foo(-1); } catch (Exception $e) { $hit = true; } if (!isset($hit)) $this->fail('No exception thrown'); unset($hit); try { foo(1); } catch (Exception $e) { $hit = true; } if (!isset($hit)) $this->fail('No exception thrown'); unset($hit); }
The divide(4,0) will then throw the expected exception and all the expect* function will pass. But note that the code $this->assertSame(0,1) will not be executed, the fact that it is a failure doesn't matter, because it will not run. The divide by zero exception causes the test method to exit.
The assertEquals() function is a builtin function in PHPUnit and is used to assert whether the actual obtained value is equals to expected value or not. This assertion will return true in the case if the expected value is the same as the actual value else returns false.
PHPUnit is a unit testing framework for the PHP programming language. It is an instance of the xUnit design for unit testing systems that began with SUnit and became popular with JUnit. Even a small software development project usually takes hours of hard work.
I think this is a very common situation in unit testing. The approach I use in this cases is using phpunit dataProviders. All works as expected, and test code become more clear and concise.
class MyTest extends PHPUnit\Framework\TestCase { public function badValues(): array { return [ [-1], [1] ]; } /** * @dataProvider badValues * @expectedException Exception */ public function testFoo($badValue): void { foo($badValue); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With