9951 explained code solutions for 126 technologies


phpunitHow to use expects twice in PHPUnit?


Using expects twice in PHPUnit is possible by using the expectException and expectExceptionMessage methods.

Example code

public function testException()
{
    $this->expectException(Exception::class);
    $this->expectExceptionMessage('Exception message');
    throw new Exception('Exception message');
}

Output example

OK (1 test, 1 assertion)

Code explanation

  • $this->expectException(Exception::class); - This line sets the expectation that an exception of type Exception will be thrown.
  • $this->expectExceptionMessage('Exception message'); - This line sets the expectation that the exception thrown will have the message Exception message.
  • throw new Exception('Exception message'); - This line throws an exception of type Exception with the message Exception message.

Helpful links

Edit this code on GitHub