有 Laravel。在本地缓存时运行测试。
这是一个严重的问题,每个人都会沉迷一次。

虽然需要在本地缓存,
想检查一下操作,看看缓存的时候会不会出错,所以想在测试前先把缓存文件删掉。

甚至官方文档都说テストを実行する前は必ずconfig:clear Artisanコマンドを使用して設定のキャッシュをクリアしてください。
https://readouble.com/laravel/9.x/ja/testing.html

所以我想出了三种可能的方法。

方法 1. 使用 Composer 脚本

作曲家.json
{
    "scripts": {
        "test": [
            "@php artisan config:clear",
            "@php artisan test"
        ]
    },
}
$ composer test

这很容易。

@php 会自动解析到正在运行的 php 进程。
https://getcomposer.org/doc/articles/scripts.md#executing-php-scripts

方法 2. 使用 Makefile

生成文件
test:
	php artisan config:clear
	php artisan test
$ make test

这也是一种简单的方法。
composer 可以用一半的字符数完成哈哈

Makefile 应该使用制表符而不是空格来缩进。

方法3.创建一个清除缓存的测试

在方法一和方法二的情况下,如果直接执行php artisan test./vendor/bin/phpunit是很自然的,但是没有清除缓存。
用 phpunit 设置执行之前似乎无法运行脚本,所以我将创建一个只清除缓存的测试。
(不知道是好是坏……)

将其放置为tests/SetupConfigClearTest.php,因为您想将其与功能和单元测试分开。

测试/设置/ConfigClearTest.php
<?php

declare(strict_types=1);

namespace Tests\Setup;

use Tests\TestCase;

final class ConfigClearTest extends TestCase
{
    /**
     * @return void
     */
    public function testConfigClear(): void
    {
        $this->artisan('config:clear');
        $this->assertFalse(file_exists(base_path('bootstrap/cache/config.php')));
    }
}

phpunit.xml Unit and Feature 上方添加安装测试。

phpunit.xml
    <testsuites>
        <testsuite name="Setup">
            <directory suffix="Test.php">./tests/Setup</directory>
        </testsuite>
        <testsuite name="Unit">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>
        <testsuite name="Feature">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>
    </testsuites>
$ php artisan test

   PASS  Tests\Setup\ConfigClearTest
  ✓ config clear

...

如果先执行ConfigClearTest就可以了。
如果不指定该选项,则在无法清除缓存的情况下继续测试(我不这么认为...)

$ php artisan test --stop-on-failure

   PASS  Tests\Setup\ConfigClearTest
  ✓ config clear

...

`--stop-on-failure` オプションを指定すればエラー出たらテストが即終了するようにできます。

概括

我个人认为方法3是最好的。
其实我并不想把它写成一个测试类,但是我觉得把它从Setup目录中分离出来会更好。

与任何方法一样,请注意,如果您指定文件并运行测试,则不会清除缓存。

$ php artisan test tests/Feature/ExampleTest.php

相关文章


原创声明:本文系作者授权爱码网发表,未经许可,不得转载;

原文地址:https://www.likecs.com/show-308626889.html

相关文章:

  • 2022-12-23
  • 2021-11-21
  • 2021-11-21
  • 2021-11-21
  • 2021-11-21
  • 2021-08-18
  • 2021-08-04
猜你喜欢
  • 2021-12-02
  • 2022-12-23
  • 2022-12-23
  • 2021-08-08
  • 2022-12-23
  • 2022-02-19
  • 2022-12-23
相关资源
相似解决方案