【问题标题】:Laravel integration testing jobsLaravel 集成测试工作
【发布时间】:2016-12-21 22:56:39
【问题描述】:

我正在尝试为我的应用运行集成测试。我有这些工作:

  • 开始工作
  • 准备工作
  • 执行作业

StartJob 调度一个或多个 PrepareJob,每个 PrepareJob 调度一个 PerformJob。

添加这个

$this->expectsJobs(
        [
            StartJobs::class,
            PrepareJob::class,
            PerformJob::class
        ]
    );

使我的测试失败并显示错误提示

1) JobsTest::testJobs
BadMethodCallException: Method Mockery_0_Illuminate_Contracts_Bus_Dispatcher::dispatchNow() does not exist on this mock object

删除 $this->expectsJobs 使我的所有测试都通过,但我不能断言给定的作业已运行,只能断言它是否将数据库修改为给定状态。

StartJobs.php

    class StartJobs extends Job implements ShouldQueue
    {
        use InteractsWithQueue;
        use DispatchesJobs;

        public function handle(Writer $writer)
        {
            $writer->info("[StartJob] Started");

            for($i=0; $i < 5; $i++)
            {
                $this->dispatch(new PrepareJob());
            }

            $this->delete();
        }

    }

PrepareJob.php

class PrepareJob  extends Job implements ShouldQueue
{
    use InteractsWithQueue;
    use DispatchesJobs;

    public function handle(Writer $writer)
    {
        $writer->info("[PrepareJob] Started");

        $this->dispatch(new PerformJob());

        $this->delete();
    }

}

PerformJob.php

class PerformJob  extends Job implements ShouldQueue
{
    use InteractsWithQueue;

    public function handle(Writer $writer)
    {
        $writer->info("[PerformJob] Started");

        $this->delete();
    }
}

JobsTest.php

class JobsTest extends TestCase
{
    /**
     * @var Dispatcher
     */
    protected $dispatcher;

    protected function setUp()
    {
        parent::setUp();
        $this->dispatcher = $this->app->make(Dispatcher::class);
    }

    public function testJobs()
    {
        $this->expectsJobs(
            [
                StartJobs::class,
                PrepareJob::class,
                PerformJob::class
            ]
        );

        $this->dispatcher->dispatch(new StartJobs());
    }
}

我认为这与我使用具体调度程序的方式有关,而 $this->expectsJob 模拟了调度程序。可能与此有关 - https://github.com/laravel/lumen-framework/issues/207。有什么办法解决这个问题?

【问题讨论】:

  • 你能给我们看看代码吗?
  • @AngadDubey 我认为代码太简单了,发布它没有意义。但是,当我一直在编写简单的作业和测试时,我发现了问题的根源。我用所有代码示例和观察修改了我的帖子

标签: php laravel phpunit laravel-queue


【解决方案1】:

对我来说,听起来好像没有 dispatchNow() 方法。在作业中,您运行 dispatch() 但错误显示 dispatchNow() 不存在。

Laravel 在某个版本之前没有 dispatchNow() 方法(我认为 Laravel 5.2 ... 不确定),但只有 dispatch()。可能是 expectsJobs 没有考虑到这一点而失败了。

您可以尝试不在一个数组中传递它,而是使用 3 个命令:

$this->expectsJobs(StartJobs::class);
$this->expectsJobs(PrepareJob::class);
$this->expectsJobs(PerformJob::class);

也许这有帮助。

【讨论】:

    猜你喜欢
    • 2013-09-08
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 2014-09-15
    • 2013-05-30
    • 1970-01-01
    • 2016-05-27
    • 2015-03-01
    相关资源
    最近更新 更多