Created
March 1, 2022 14:58
-
-
Save scrubmx/7571e9663963e33d17b7c5dcede11e75 to your computer and use it in GitHub Desktop.
Assert exception was reported by Laravel (useful for testing code inside rescue)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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