To test the JobFailedListener functionality, especially the part where it checks if a job implements the IsRetryableJob interface, you can use Laravel's testing capabilities. Here's a step-by-step guide on how to set up a test for this:
-
Create a Test Class: You can use Laravel's artisan command to generate a test class if you haven't already.
php artisan make:test JobFailedListenerTest -
Mock the Dependencies: You'll need to mock the
JobFailedevent and any other dependencies like theRetryableJobmodel and theLogfacade. -
Write the Test: Here's an example of how you might write a test for the
JobFailedListener.namespace Tests\Unit; use App\Listeners\JobFailedListener; use App\Models\RetryableJob; use Illuminate\Support\Facades\Log; use Laravel\Horizon\Events\JobFailed; use PHPUnit\Framework\TestCase; use Mockery; class JobFailedListenerTest extends TestCase { public function test_it_handles_retryable_jobs() { // Mock the job and event $job = Mockery::mock('stdClass'); $job->shouldReceive('resolveName')->andReturn('App\Jobs\SomeRetryableJob'); $job->shouldReceive('payload')->andReturn([ 'data' => [ 'command' => 'SomeCommandData' ] ]); $exception = new \Exception('Test exception'); $event = new JobFailed('connection', $job, $exception); // Mock the RetryableJob model $retryableJobMock = Mockery::mock('alias:App\Models\RetryableJob'); $retryableJobMock->shouldReceive('create')->once(); // Mock the Log facade Log::shouldReceive('channel->info')->once(); // Instantiate the listener and call the handle method $listener = new JobFailedListener(); $listener->handle($event); // Assert that the RetryableJob was created $this->assertTrue(true); // This is just a placeholder to ensure the test runs } } -
Run the Test: Use PHPUnit to run your test and ensure everything is working as expected.
./vendor/bin/phpunit --filter=JobFailedListenerTest
This test checks that when a job that implements the IsRetryableJob interface fails, the JobFailedListener logs the failure and creates a RetryableJob record. Adjust the mock expectations and assertions as needed to fit your actual implementation details.