【问题标题】:PHPUnit tests actually runs the code instead of just testingPHPUnit 测试实际上运行代码而不是仅仅测试
【发布时间】:2021-09-11 02:56:30
【问题描述】:

我不确定我是否正确设置它,因为这是我第一次使用 PHPUnit 测试。

我想测试一个向用户发送电子邮件的特定控制台命令。

这是我的单元测试。

     /**
     * @test
     */
    public function test_expiring_assessment_command_success()
    {
        $user = $this->getOrCreateTestUser();
        $assessment = $this->getOrCreateTestOnlineVisit($user, 'cancelled');

        Log::debug($assessment); //this log logs the factory created assessment
        Log::debug(env('APP_ENV')); //testing

        $this->artisan('process:send-visit-emails');
    }

This is the code in my SendVistEmails.php

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $from = Carbon::now()->subDays(7)->startOfDay();
        $to = $from->copy()->endOfDay();

        $assessments = Assessment::query()
            ->whereIn('status', ['pending_pause', 'pending'])
            ->whereNotNull('response_required_from')
            ->whereBetween('response_required_from', [$from, $to])
            ->select('details', 'status')
            ->get();

        foreach ($assessments as $a){
            Log::debug($a); //this logs assessments present in DB instead of the one created in my test.
        }

        $assessments->each->expire();
    }

现在,当我运行 phpunit tests 时,它只是与代码交互并向数据库中的所有用户发送电子邮件。

我只想在我的 SendVistEmails.php 代码中运行命令进行测试,当我记录 $a 时,它应该只有我的单元测试创​​建的评估,而不是来自 DB 的评估。

我花了两天时间阅读了这么多文档,但无法弄清楚我错过了什么。

【问题讨论】:

  • 创建一个只记录日志的处理程序。然后测试该代码。但是,由于这是调试日志记录,因此日志记录本身就是生产系统的“测试”。您通常不需要对此进行测试(可能除了一项向您显示日志记录以您认为的方式工作的测试,例如,在一个测试中,您只在一个孤立的场景中测试您的日志记录期望)。

标签: php unit-testing testing laravel-5 phpunit


【解决方案1】:

由于你使用Assessment::query()中的数据库,所以它调用配置的数据库。

处理方法有很多种,其中两种:

  1. 使用另一个配置的数据库进行测试; see this answer of "Laravel: Use different database for testing and local"

  2. 模拟评估门面以返回测试数据; see the laravel documentation

【讨论】:

    猜你喜欢
    • 2015-08-12
    • 2020-05-14
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    相关资源
    最近更新 更多