1

How to test job arguments if Exception is thrown after job is dispatched. This test below returns green, but i found no way to test job arguments.

Code:

<?php

namespace Tests\Feature;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Tests\TestCase;

class SomeJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public function handle() {}
}

class NothingTest extends TestCase
{
    /** @test */
    public function dispatch_test()
    {
        $this->expectException(\Exception::class);
        $this->expectsJobs(SomeJob::class);

        // job dispatched and Exception thrown afterwards
        dispatch(new SomeJob("argument to test"));
        throw new \Exception();
    }
}

3 Answers 3

1

I actually ran into this earlier today myself. What I did to solve this issue was by using the withoutJobs() method instead. (Internally expectsJobs() calls this as well.) You can then assert against the dispatchedJobs property.

Because you are also 'expecting' and exception in your test you should wrap this in a callback and register it in a beforeApplicationDestroyed()

class SomeJob {
    private $argument;

    public function __construct($argument)
    {
        $this->argument = $argument;
    }
}


class NothingTest extends TestCase
{
    /** @test */
    public function dispatch_test()
    {
        $this->expectException(\Exception::class);
        $this->beforeApplicationDestroyed(function () {
            // This part depends on how you would like to design this. You could
            // use public properties, add a getter method on your job or use
            // something like reflection to compare the properties.
            $dispatchedJob = $this->dispatchedJobs[0];
            $this->assertEquals(
                'argument to test',
                $this->getValue($dispatchedJob, 'argument')
            );
        });

        // job dispatched and Exception thrown afterwards
        dispatch(new SomeJob("argument to test"));
        throw new \Exception();
    }

    protected function getValue($object, $name)
    {
        $ro = new \ReflectionObject($object);
        $property = $ro->getProperty($name);
        $property->setAccessible(true);

        return $property->getValue($object);
    }
}
3
  • you have mention Reflection - i try and found no way to get values of passed arguments. is it actually possible? Commented Apr 7, 2017 at 11:49
  • I don't think you can actually get the passes arguments if you don't assign them to properties. I've updated the example to show how to get the value of a private property Commented Apr 8, 2017 at 20:02
  • I've found a way to test arguments without reflections using just IOC Container. Check it out below. Is it better? Commented Apr 24, 2017 at 20:11
0

ok. can test like this code below. test looks nice, but you must use public properties and assign all arguments to the properties.

<?php

namespace Tests\Examples;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Tests\TestCase;

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

    public $arg1;
    public $arg2;

    public function __construct($arg1, $arg2) 
    {
        $this->arg1 = $arg1;
        $this->arg2 = $arg2;
    }
    public function handle() {}
}

class JobTest extends TestCase
{
    /** @test */
    public function dispatch_test()
    {
        $this->expectException(\Exception::class);
        $this->expectsJobs(SomeJob::class);

        $this->testJobInstance(SomeJob::class, function($job){
            $this->assertEquals('arg1', $job->arg1);
            $this->assertEquals('arg2', $job->arg2);
        });

        // job dispatched and Exception thrown afterwards
        dispatch(new SomeJob("arg1", "arg2"));
        throw new \Exception();
    }


    // will be pushed up to TestCase
    protected function testJobInstance($class, callable $callback)
    {
        $this->beforeApplicationDestroyed(function () use($class, $callback) {

            $job = collect($this->dispatchedJobs)->filter(function($job) use($class) {
                return get_class($job) == $class;
            })->first();

            $callback($job);

        });
    }
}
0

Ok, the better way found...

I've made a helper function to dispatch jobs from IOC - it makes a lot easier to test jobs.

/**
 * @param string | object $job
 * @param array | null $args - associative array of arguments ['agr1' => 'value', 'arg2' => 2]
 * @return mixed
 */
function dispatch_from_ioc($job, ? array $args)
{
    if (is_string($job)) {
        $job = app()->makeWith($job, $args);
    }

    return app(Dispatcher::class)->dispatch($job);
}

so now i can test job arguments like this:

/** @test */
public function test_jobs_arguments()
{
    $this->app->bind(
        RealJob::class,
        function($app, $args){

            // assertions against arguments
            $this->assertEquals("argument", $args["arg"]);
            $this->assertEquals([], $args["arg2"]);

            return new FakeJob;
        }
    );

    // System under test
    dispatch_from_ioc(RealJob::class, ["arg" => "argument", "arg2" => []]);
}

Fake Job class

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class FakeJob extends Job
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public function __construct() {}
    public function handle() {}
}

Does it makes sense? :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.