Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test for multiple exceptions with PHPUnit?

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);  } 
like image 821
etheros Avatar asked Oct 20 '09 11:10

etheros


People also ask

How do I assert exceptions in PHPUnit?

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.

What is assertion in PHPUnit?

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.

What is a PHPUnit test?

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.


1 Answers

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);     } } 
like image 65
Nicolò Martini Avatar answered Sep 23 '22 21:09

Nicolò Martini