Php unit test assert exception

Php how to assert exception in phpunit

In the annotation form, you have to use the full namespace to the class name for it to work: The alternative: This is more readable, more explicit, flexible (automated refactoring/renaming would be a doddle in most editors like PHPStorm), is less code to write, and is in line with the standard test method setup of the 3 phases in correct order, Arrange, Assert, Act . It also can be a further element, e.g. , in the array returned by the data provider method (and then in the test method: ).

PHPUnit using annotations to assert exception vs method call

Using expectException() is considered best practice, see this article.

There’s a few clear advantages for me on why I’d choose to use the method rather than the annotation.

In the annotation form, you have to use the full namespace to the class name for it to work:

@expectedException MyException // Not found unless it is within the current namespace @expectedException \Some\Deep\Namespace\MyException // works 
$this->expectException(MyException::class); // works, with a 'use' statement 

This is more readable, more explicit, flexible (automated refactoring/renaming would be a doddle in most editors like PHPStorm), is less code to write, and is in line with the standard test method setup of the 3 phases in correct order, Arrange, Assert, Act . Lastly, the annotation internally would need to be parsed, and would only call the expectException method anyway. So it’s going to be more efficient as well.

Читайте также:  Python tkinter border color

How to Test Errors and Exceptions using PHPUnit, PHP Testing Tutorial — How to Test Errors and Exceptions using PHPUnit Learn how to Duration: 14:23

How to Test Errors and Exceptions using PHPUnit

How to test exceptions using a data provider in PHPUnit?

PHPUnit doesn’t provide this combination. But this can be implemented with a simple trick:

Separate test methods for normal and exception testing.

class TestMyClass < /** * @dataProvider provideDataForFoo */ public function testFoo($paramBar, $paramBuz, $expected) < $myObject = new MyClass(); $this->assertEquals($expected, $myObject->foo($paramBar, $paramBuz)); > public function provideDataForFoo() < return [ ['expected lorem', 'bar lorem', 'buz lorem'], ['expected ipsum', 'bar ipsum', 'buz ipsum'], ]; >/** * @dataProvider provideDataForFooException */ public function testFooException($paramBar, $paramBuz, $expectedException) < $myObject = new MyClass(); $this->expectException($expectedException); $myObject->foo($paramBar, $paramBuz); > public function provideDataForFooException() < return [ ['expected exception', 'bar invalid argument', '\My\Exception\Fully\Qualified\Name'], ]; >> 

a. One test method and using the Reflection API.

We have only one test method. The data provider method returns an array, where to elements for the $expected test method input can be Exceptions . If the $expected is an Exception we handle this case with expectException(. ) , otherwise as a «normal» test case.

b. One test method and using an «exception» flag.

Theoretically a method can return an Exception . To consider this case we have to introduce a flag like «testItForException» and provide this information to the test method. It also can be a further element, e.g. exception , in the array returned by the data provider method (and then in the test method: if(! (empty($exception)) < test it as normal >else ) ).

Instead of the annotation you can also use $this->setExpectedExceptionRegExp() with the arguments

$exceptionName — mixed (class name or exception instance) $exceptionMessageRegExp — string (optional regular expression) $exceptionCode — integer (optional exception code) 

Note: The old setExpectedException() method has been deprecated in PHPUnit 5.2

Читайте также:  Html div style float left

This means, you can pass an exception class name via data provider. If it is not empty, call setExpectedExceptionRegExp()

Another advantage of the method over the annotation is that you can be more specific about where the exception is expected, if you don’t call the method at the beginning of the test.

How to test exceptions using a data provider in PHPUnit?, It also can be a further element, e.g. exception , in the array returned by the data provider method (and then in the test method: if(! (empty($

How to catch an exception in phpunit

Ensure you call the following method first:

$client->catchExceptions(false); 
public function testUserCantUpdateABookingFromAnotherOrganisation() < $this->expectException(NotFoundHttpException::class); $client = static::createClient(); $client->catchExceptions(false); $client->request('GET', '/foo/bar'); $client->request( 'PUT', '/api/bookings/' . $bookingIdToUpdate, [ 'auth_bearer' => $token, 'json' => [ 'requestedBy' => 'a new value for this field', ], ] ); self::assertResponseStatusCodeSame(Response::HTTP_NOT_FOUND, 'This user is not expected to be able to update this booking'); > 

Php — How do I test for an exact Exception message, rather than a, You can use $this->expectExceptionMessage() to handle this. Example: $this->expectException(InvalidArgumentException::class);

How to check exception AND EXCEPTION MESSAGE in phpUnit 6?

$this->expectException(NotFoundException::class); $this->expectExceptionMessage('Not Found'); 

Phpunit expectException() wrong exception name, I got this failure: Failed asserting that exception of type «TypeError» matches expected exception «InvalidArgumentException». the question is

Источник

phpunit Assertions Assert an Exception is Thrown

PHPUnit provides the following functions to watch for thrown exceptions, which were released with 5.2.0:

  • expectException($exception)
  • expectExceptionMessage($message)
  • expectExceptionCode($code)
  • expectExceptionMessageRegExp($messageRegExp)

These are used to watch for an exception to be thrown and inspect the properties of that exception.

Let’s start with a math function that divides (just for simplicity). It will raise an exception if the denominator is zero.

function divide($numerator, $denominator) < if ($denominator !== 0) < return $numerator/$denominator; >else < throw new \Exception("Cannot divide by zero", 100); >> 
class DivideTest extends PHPUnit_Framework_TestCase < public function test_divide() < $this->assertSame(2,divide(4,2)); $this->expectException("Exception"); $this->expectExceptionCode(100); $this->expectExceptionMessage("Cannot divide by zero"); $this->expectExceptionMessageRegExp('/divide by zero$/'); // the expectations have been set up, now run the code // that should throw the exception divide(4,0); // The following code will not execute, the method has exited $this->assertSame(0,1); > > 

The test_divide() function starts by asserting that the function correctly divided 4 by 2 and answered 2. This assertion will pass.

Читайте также:  Отчет времени до даты html

Next, the expectations for the upcoming exception are set. Notice, they are set before the code that will throw the exception. All four assertions are shown for demonstration purposes, but this is normally not necessary.

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. This can be a source of confusion while debugging.

pdf

PDF — Download phpunit for free

Источник

Оцените статью