codeception/assert-throws
Adds assertThrows-style assertions to Codeception, letting you easily verify exceptions in tests. Assert the exception type and optionally message/code when running a callable, making negative-path testing clearer and less verbose.
assertDatabaseHas() or assertRedirect().Laravel\Testing\TestCase, enabling HTTP, feature, and unit tests to assert exceptions without disrupting workflows.ValidationException, HttpResponseException).expectException(), this package continues test execution after failure, risking false positives if subsequent assertions depend on the exception’s side effects.Illuminate\Auth\AuthenticationException) may require type hints or wrapper methods for full compatibility.expectException()?ModelNotFoundException) that need tailored assertions?try-catch or expectException() without disrupting existing tests?Laravel\Testing\TestCase for HTTP/feature tests.AssertThrowsTrait) for compatibility.Codeception\Test\Unit or Codeception\Test\Acceptance.AuthTest.php).expectException() or try-catch logic.expectException() calls and migrate to assertThrows().// Before
$this->expectException(ValidationException::class);
// After
$this->assertThrows(ValidationException::class, fn() => $validator->validate());
assertLaravelValidationException()) to standardize exception types.codeception/codeception is ≥4.0.composer require --dev codeception/assert-throws
use AssertThrows\AssertThrowsTrait;
class MyTest extends \Codeception\Test\Unit {
use AssertThrowsTrait;
}
use AssertThrows\AssertThrowsTrait;
class MyTest extends \Tests\TestCase {
use AssertThrowsTrait;
}
--verbose to catch unexpected assertion failures.codeception/codeception for breaking changes (MIT license ensures minimal risk).| Failure Type | Likelihood | Mitigation |
|---|---|---|
| Silent assertion failures | Medium | Use --verbose in CI/CD. |
| Incorrect exception types | High | Pair with instanceof checks. |
| Flaky tests (race conditions) | Low | Avoid in async/queue tests. |
| Test pollution (side effects) | Medium | Isolate assertions in dedicated methods. |
assertThrows() vs. expectException().ValidationException, HttpResponseException).$this->assertThrows(
UnauthorizedException::class,
fn() => $this->actingAs($user)->delete('/admin')
);
protected function assertValidationFails(callable $action, string $message = '') {
$this->assertThrows(
ValidationException::class,
$action,
$message
);
}
refreshDatabase() to avoid polluted test states:
public function testDeleteRequiresPermission() {
$this->refreshDatabase();
$this->assertThrows(AuthorizationException::class, fn() => $this->delete('/admin'));
}
How can I help you explore Laravel packages today?