Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[9.x] Add closure based exceptions testing #42155

Merged
merged 2 commits into from
May 3, 2022

Conversation

shaffe-fr
Copy link
Contributor

@shaffe-fr shaffe-fr commented Apr 27, 2022

Hi all,

This adds new ways to test exception handling using closures.

// Ensure that an exception is thrown
$this->assertThrows(fn () => throw Exception(''));

// Ensure that a specific type of exception is thrown
$this->assertThrows(
    fn () => (new SomeActionThatThrowsExceptions)->execute(), 
    CustomException::class
);

// Ensure that an exception is thrown with a specific message
$this->assertThrows(fn () => throw Exception('My message'), Exception::class, 'My message');

// Ensure that no exceptions are thrown
$this->assertDoesntThrow(
    fn () => (new SomeActionThatWorksFine)->execute()
);

// Ensure that a specific type of exception is thrown with the given message
$this->assertThrowsWithMessage(
    fn () => (new SomeActionThatThrowsExceptionsWithCustomMessage)->execute(), 
    'My custom exception message'
);

@shaffe-fr shaffe-fr force-pushed the feat/assert-exception branch 8 times, most recently from 43218e1 to 7c9246d Compare April 29, 2022 16:25
@taylorotwell
Copy link
Member

Can you elaborate a bit on why you would need assertDoesntThrow? Wouldn't PHPUnit fail anyways if there was an unexpected exception?

@taylorotwell
Copy link
Member

Please mark as ready for review once you have responded.

@taylorotwell taylorotwell marked this pull request as draft May 2, 2022 14:48
@shaffe-fr shaffe-fr force-pushed the feat/assert-exception branch from 7c9246d to 5bf0bfc Compare May 2, 2022 15:05
@shaffe-fr
Copy link
Contributor Author

Hi @taylorotwell,
assertDoesntThrow will only bubble exceptions of the given type. Other exceptions will be ignored.
After some thoughts, I don't think it's a behaviour we want or expect for an assertion with this name.
I removed the method.

@shaffe-fr shaffe-fr marked this pull request as ready for review May 2, 2022 15:09
@DarkGhostHunter
Copy link
Contributor

image

You can also use a try-catch block if you need to assert something during the exception handling.

@shaffe-fr
Copy link
Contributor Author

shaffe-fr commented May 3, 2022

@DarkGhostHunter I think this is a quality of life improvement among many others in Laravel.
One might argue the tap helper is overkill because we can use separated statements.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants