Annaro's avatar

How to test code inside a job?

In ANOTHER test, i am testing that the job is actually pushed to the queue, using Queue::fake() :

    /** @test */
    public function job_is_dispatched()
    {
       // some code

        Queue::fake();
        $response = $this->post(route('runOrScheduleAction'));
        sleep(1);
        Queue::assertPushed(RunJob::class, 1);
    }

Now i'd like to test the code of the job. So i want to actually execute the job. It must be a stupid question, but how do i do this? Is there an equivalent to Queue::fake() that is not "fake". Some kind of Queue:::real() haha?

RunJob.php

class RunJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $user;
    public $method;
    public $args;

    public function __construct($user, $method = null, $args = null)
    {
        $this->user = $user;
        $this->method = $method;
        $this->args = $args;        
    }

    public function handle()
    {
        // some code that needs to be tested
    }

I tried with Queue::push() but i can't get it to work, i get an error:

Queue::push(RunJob::class, array(
            'user' => auth()->user(),
            'method' => 'share_post',
            'args' => $this->parametersForSharePostAction()
        ));
Illuminate\Contracts\Container\BindingResolutionException: Unresolvable dependency resolving [Parameter #0 [ <required> $user ]] in class App\Jobs\RunJob
0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

Test the class in isolation of the Queue; you're testing the Job, not the Queue.

$user = User::factory()->make();
$job = new RunJob($user, 'share_post');
// make assertion(s) on the side-effects/result of `$job->handle()`
1 like

Please or to participate in this conversation.