Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit assert that an exception was thrown?

Does anyone know whether there is an assert or something like that which can test whether an exception was thrown in the code being tested?

like image 539
Felipe Avatar asked Apr 16 '11 00:04

Felipe


People also ask

How to handle exception In PHPUnit?

Use expectExceptionMessage if the message is important, or if it is the only way to see where something went wrong. Use try catch if you need to validate specific properties of the exception. For this post, PHPUnit 9.5 and PHP 8.0 were used. If you want to run the tests for yourself, you can find them on github.

How do you assert exceptions in JUnit 4?

When using JUnit 4, we can simply use the expected attribute of the @Test annotation to declare that we expect an exception to be thrown anywhere in the annotated test method. In this example, we've declared that we're expecting our test code to result in a NullPointerException.


1 Answers

<?php require_once 'PHPUnit/Framework.php';  class ExceptionTest extends PHPUnit_Framework_TestCase {     public function testException()     {         $this->expectException(InvalidArgumentException::class);         // or for PHPUnit < 5.2         // $this->setExpectedException(InvalidArgumentException::class);          //...and then add your test code that generates the exception          exampleMethod($anInvalidArgument);     } } 

expectException() PHPUnit documentation

PHPUnit author article provides detailed explanation on testing exceptions best practices.

like image 140
Frank Farmer Avatar answered Oct 27 '22 00:10

Frank Farmer