Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

how to test that function throws an exception in pest

Writing a test to expect a test to throw an exception can be done as follows:

it('throws exception', function () {
    throw new Exception('Something happened.');
})->throws(Exception::class);

    
If you wish to assert the exception message too, you need to give a second argument to the throws method:

it('throws exception', function () {
    throw new Exception('Something happened.');
})->throws(Exception::class, 'Something happened.');

    
If you're only interested in the message, and the exception type isn't important, you can just provide the message by itself:

it('throws exception', function () {
    throw new Exception('Something happened.');
})->throws('Something happened.');

    
You may also use the throwsIf method to conditional assert an exception if a given boolean expression evaluates to true:

it('throwsIf exception', function () {
    // ..
})->throwsIf(fn() => DB::getDriverName() === 'mysql', Exception::class, 'MySQL is not supported.');

    
You may also assert one or more exceptions inside your test function with Expectations' method toThrow()
 
PREVIOUS NEXT
Tagged: #test #function #throws #exception #pest
ADD COMMENT
Topic
Name
4+4 =