Merge pull request #371 from mertasan/throwsif

Add `throwsIf` exception
This commit is contained in:
Nuno Maduro
2021-09-24 21:10:56 +01:00
committed by GitHub
3 changed files with 45 additions and 0 deletions

View File

@ -78,6 +78,26 @@ final class TestCall
return $this; return $this;
} }
/**
* Asserts that the test throws the given `$exceptionClass` when called if the given condition is true.
*
* @param Closure|bool|int $condition
*/
public function throwsIf($condition, string $exception, string $exceptionMessage = null): TestCall
{
$condition = is_callable($condition)
? $condition
: Closure::fromCallable(function () use ($condition): bool {
return (bool) $condition;
});
if ($condition() === true) {
return $this->throws($exception, $exceptionMessage);
}
return $this;
}
/** /**
* Runs the current test multiple times with * Runs the current test multiple times with
* each item of the given `iterable`. * each item of the given `iterable`.

View File

@ -107,6 +107,11 @@
✓ it catch exceptions ✓ it catch exceptions
✓ it catch exceptions and messages ✓ it catch exceptions and messages
✓ it can just define the message ✓ it can just define the message
✓ it not catch exceptions if given condition is false
✓ it catch exceptions if given condition is true
✓ it catch exceptions and messages if given condition is true
✓ it can just define the message if given condition is true
✓ it can just define the message if given condition is 1
PASS Tests\Features\Expect\HigherOrder\methods PASS Tests\Features\Expect\HigherOrder\methods
✓ it can access methods ✓ it can access methods

View File

@ -17,3 +17,23 @@ it('catch exceptions and messages', function () {
it('can just define the message', function () { it('can just define the message', function () {
throw new Exception('Something bad happened'); throw new Exception('Something bad happened');
})->throws('Something bad happened'); })->throws('Something bad happened');
it('not catch exceptions if given condition is false', function () {
$this->assertTrue(true);
})->throwsIf(false, Exception::class);
it('catch exceptions if given condition is true', function () {
throw new Exception('Something bad happened');
})->throwsIf(function () { return true; }, Exception::class);
it('catch exceptions and messages if given condition is true', function () {
throw new Exception('Something bad happened');
})->throwsIf(true, Exception::class, 'Something bad happened');
it('can just define the message if given condition is true', function () {
throw new Exception('Something bad happened');
})->throwsIf(true, 'Something bad happened');
it('can just define the message if given condition is 1', function () {
throw new Exception('Something bad happened');
})->throwsIf(1, 'Something bad happened');