PHP code example of jchook / phpunit-assert-throws
1. Go to this page and download the library: Download jchook/phpunit-assert-throws library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
jchook / phpunit-assert-throws example snippets
// Within your test case...
$x = new MyTestedObject();
$this->assertThrows(
MyException::class,
fn() => $x->doSomethingBad()
);
declare(strict_types=1);
// PHPUnit
use PHPUnit\Framework\TestCase;
// This library
use Jchook\AssertThrows\AssertThrows;
// Your classes
use MyNamespace\MyException;
use MyNamespace\MyObject;
final class MyTest extends TestCase
{
use AssertThrows; // <--- adds the assertThrows method
public function testMyObject()
{
$obj = new MyObject();
// Ensure that a function throws a specific exception
$this->assertThrows(MyException::class, function() use ($obj) {
$obj->doSomethingBad();
});
// Test custom aspects of a custom extension class
$this->assertThrows(MyException::class,
function() use ($obj) {
$obj->doSomethingBad();
},
function($exception) {
$this->assertEquals('Expected value', $exception->getCustomThing());
$this->assertEquals(123, $exception->getCode());
}
);
// Test that a specific method does *NOT* throw
$this->assertNotThrows(MyException::class, function() use ($obj) {
$obj->doSomethingGood();
});
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.