'Laravel phpunit testing artisan command to run jobs assertPushed always fails

I have an artisan command to run a batch of jobs, reason I am using command as this will just be a one time thing to migrate alot of data(20k records) hence without dispatching job, I will always run out of memory.

my command handle function

     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        Model::query()
            ->cursor()
            ->tap(function ($query) {
                $count = $query->count();

                $this->progressBar = $this->output->createProgressBar($count);

                $this->info("number of records to be processed");
            })
            ->each(function ($model) {
                TestJob::dispatchNow($model);

                $this->progressBar->advance();
            });

        if ($this->progressBar) {
            $this->progressBar->finish();
        }
        return 0;
    }

My Unit Test

     * A basic unit test example.
     *
     * @return void
     */
    public function test_command_dispatch_job()
    {
        Queue::fake();

        Artisan::call('random:test-job');

        Queue::assertPushed(TestJob::class);

        $this->assertTrue(true);
    }

I always get this error

The expected [App\Jobs\TestJob] job was not pushed.


Solution 1:[1]

You need to replace:

Artisan::call('random:test-job');

to

TestJob::dispatch()->onQueue('run');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Carola