防止 phpunit 启动所有功能

Preventing phpunit from launching all functions

如何防止 phpunit 启动我不想要的函数?

<?php

namespace App\Tests;

use App\Core\Security\ModuleService;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class moduleTest extends WebTestCase
{
    /**
     * @var ModuleService
     */
    private ModuleService $moduleService;

    /**
     * moduleTest constructor.
     * @param ModuleService $moduleService
     */
    public function __construct(ModuleService $moduleService)
    {
        $this->moduleService = $moduleService;
    }
    
    public function testModule()
    {
        $modules = $this->moduleService->getAllModules();
    }
}




phpunit 尝试测试构造方法并崩溃

PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function App\Tests\moduleTest::__construct(), 0 passed in /vendor/phpunit/phpunit/src/Framework/TestBuilder.php on line 138 and exactly 1 expected in /tests/moduleTest.php:20

更新

试过这样做

public function setUp(ModuleService $moduleService) : void
    {
        $this->moduleService = $moduleService;
    }

但现在我收到了这个错误:

ArgumentCountError: Too few arguments to function App\Tests\moduleTest::setUp(), 0 passed in /vendor/phpunit/phpunit/src/Framework/TestCase.php on line 1126 and exactly 1 expected

在测试中您不想使用构造函数。 Symfony 将尝试自动装配您不想要的服务,因为您希望能够模拟辅助服务。

为防止出现这种情况,您删除了构造函数并改为使用 setUp 函数。 PHPUnit 的工作方式是 setUp 函数在每次测试之前总是 运行 。所以在这里你可以实例化你正在测试的服务(class)。

一个简单的设置函数如下所示:

private ModuleService $moduleService;

public function setUp(): void
{
    $this->moduleService = new ModuleService();
}

然后在您的测试中,您将像往常一样使用它们:

public function testStuff()
{
    $result = $this->moduleService->doStuff();
    $this->assertEquals('stuff', $result);
}

如果您正在测试的服务具有依赖性(大多数服务都有),您应该像这样模拟它们:

private ModuleService $moduleService;
private MockObject $dependancyServiceMock;


public function setUp(): void
{
    $this->dependancyServiceMock = $this->createMock(DependancyService::class);
    $this->moduleService = new ModuleService($this->dependancyServiceMock);
}

通过这种方式,您正在测试的服务不受任何外部影响,您可以完全控制它,而无需 Symfony 自动装配它或其他服务执行您无法控制的事情。