您好,我正在尝试为 symfony4 控制台命令创建单元测试,但无法正确注入(inject)依赖项。我对 symfony4 很陌生,所以也许这对你们来说是一个基本问题。
我的单元测试如下所示:
<?php
namespace App\Tests\Command;
use App\Command\ExecuteSalesTaskCommand;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Console\Tester\CommandTester;
use Psr\Log\LoggerInterface;
use App\Repository\TaskRepository;
class ExeculteSalesTaskCommandTest extends KernelTestCase
{
/**
* @param LoggerInterface $logger
* @param TaskRepository $taskRepository
*/
public function testExecute(LoggerInterface $logger, TaskRepository $taskRepository)
{
$kernel = self::bootKernel();
$application = new Application($kernel);
$application->add(new ExecuteSalesTaskCommand($logger,$taskRepository));
# UPDATED
$logger = self::$kernel->getContainer()->get(LoggerInterface::class);
$taskRepository = self::$kernel->getContainer()->get(TaskRepository::class);
$command = $application->find('app:execute-sales-task');
$commandTester = new CommandTester($command);
$commandTester->execute(
[
'command' => $command->getName(),
]
);
// the output of the command in the console
$output = $commandTester->getDisplay();
$this->assertContains('Execute sales resulted: ', $output);
}
}
我的问题是我遇到这样的注入(inject)错误:
ArgumentCountError: Too few arguments to function App\Tests\Command\ExeculteSalesTaskCommandTest::testExecute(), 0 passed and exactly 2 expected
更新: 当我从容器中获取依赖项时,出现这种错误:
There was 1 error:
1) App\Tests\Command\ExeculteSalesTaskCommandTest::testExecute Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: The "Psr\Log\LoggerInterface" service or alias has been removed or inlined when the container was compiled. You should either make it public, or stop using the container directly and use dependency injection instead.
如何正确注入(inject)必要的依赖项,以便创建 ExecuteSalesTaskCommand 的实例?
最佳答案
我发现问题是我尝试手动加载依赖项。使用 Autowiring ,如下所示:
public function testExecute()
{
$dotenv = new Dotenv();
$dotenv->load(__DIR__.'/.env.test');
$kernel = self::bootKernel();
$application = new Application($kernel);
$executeSalesCommand = self::$kernel->getContainer()->get(
'console.command.public_alias.App\Command\ExecuteSalesTaskCommand'
);
$application->add($executeSalesCommand);
$command = $application->find('app:execute-sales-task');
$commandTester = new CommandTester($command);
$commandTester->execute(
[
'command' => $command->getName(),
]
);
// the output of the command in the console
$output = $commandTester->getDisplay();
// do your asserting stuff
}
您需要从内核容器获取命令本身。现在可以了。
关于PHP symfony4 : Dependency injection inside KernelTestCase for command,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49920398/