Skip to content

Instantly share code, notes, and snippets.

@scrubmx
Created March 1, 2022 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scrubmx/7571e9663963e33d17b7c5dcede11e75 to your computer and use it in GitHub Desktop.
Save scrubmx/7571e9663963e33d17b7c5dcede11e75 to your computer and use it in GitHub Desktop.
Assert exception was reported by Laravel (useful for testing code inside rescue)
<?php
use Tests\TestCase;
class MyTest extends TestCase
{
/**
* Sets up an expectation for an exception to be reported by the code under test.
*/
protected function expectReportedExceptionMessage(string $message): static
{
$this->partialMock(ExceptionHandler::class)
->shouldReceive('report')->atLeast()->once()
->withArgs(fn ($e) => $message === $e->getMessage() || $this->fail("Failed asserting that exception with message '$message' is reported"));
return $this;
}
/** @test */
public function it_throws_and_gets_rescued()
{
User::factory()->create(['balance' => 0]);
$this->expectReportedExceptionMessage('Not enough funds available.');
// This is a dumb example, but you get the idea...
rescue(fn () => $user->subscribe());
}
}
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
public function subscribe()
{
if ($this->balance <= 0) {
throw new \Exception('Not enough funds available.');
}
// ...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment