PHP symfony4:内核测试用例中的依赖注入命令



您好,我正在尝试为 symfony4 控制台命令创建一个单元测试,但我无法正确注入依赖项。我对symfony4很陌生,所以也许这对你们来说是一个基本问题。

我的单元测试如下所示:

<?php
namespace AppTestsCommand;
use AppCommandExecuteSalesTaskCommand;
use SymfonyBundleFrameworkBundleConsoleApplication;
use SymfonyBundleFrameworkBundleTestKernelTestCase;
use SymfonyComponentConsoleTesterCommandTester;
use PsrLogLoggerInterface;
use AppRepositoryTaskRepository;
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);
}
}

我的问题是我收到这样的注入错误:

参数

计数错误:参数太少,无法正常工作 App\Tests\Command\ExeculteSalesTaskCommandTest::testExecute(), 0 通过并且正好 2 个预期

更新: 当我从容器中获取依赖项时,出现此类错误:

有 1 个错误:

1) App\Tests\Command\ExeculteSalesTaskCommandTest::testExecute Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: "Psr\Log\LoggerInterface"服务或别名已被删除,或 编译容器时内联。你应该要么成功 公共,或停止直接使用容器并使用依赖项 注射代替。

如何正确注入必要的依赖项,以便创建 ExecuteSalesTaskCommand 的实例?

好吧,我发现问题是我试图手动加载依赖项。请改用自动连线,如下所示:

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.AppCommandExecuteSalesTaskCommand'
);
$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
// BaseCommandTester.php
/**
* This is basis for the writing tests, that will cover commands
*
*/
namespace AppTestsBase;
use SymfonyBundleFrameworkBundleTestKernelTestCase;
use SymfonyBundleFrameworkBundleConsoleApplication;
use SymfonyComponentDotenvDotenv;
class BaseCommandTester extends KernelTestCase
{
/**
* @var
*/
private $application;
/**
* to set test environment and initiate application kernel
*/
public function setUp()
{
/**
* get test env
*/
$dotenv = new Dotenv();
$dotenv->load('/var/www/.env.test');
/**
* boot kernel
*/
$kernel = self::bootKernel();
$this->application = new Application($kernel);
parent::setUp();
}
/**
* @return mixed
*/
public function getApplication()
{
return $this->application;
}
/**
* @param mixed $application
*/
public function setApplication($application)
{
$this->application = $application;
}
}

测试用例

// FeedUpdaterCommandTest.php
<?php
namespace AppTestsCommand;
use AppTestsBaseBaseCommandTester;
use SymfonyComponentConsoleTesterCommandTester;
class FeedUpdaterCommandTest extends BaseCommandTester
{
/**
* test to update all feeds
*/
public function testExecuteUpdateAll() {
/**
* init command tester and executre
*/
$commandName = 'app:feedUpdater';
$expectedResult = '[OK] Update Success Feed Type : All';
$command = $this->getApplication()->find($commandName);
$commandTester = new CommandTester($command);
$commandTester->execute(array(
'command' => $command->getName()
));
/**
* get result and compare output
*/
$result = trim($commandTester->getDisplay());
$this->assertEquals($result, $expectedResult);
}
}

测试运行结果

#Run tests
root@xxx:/var/www# bin/phpunit tests/Command
#!/usr/bin/env php
PHPUnit 6.5.13 by Sebastian Bergmann and contributors.
Testing tests/Command
2018-11-28T07:47:39+00:00 [alert] Successful update of popularProducts Feeds!
2018-11-28T07:47:39+00:00 [alert] Successful update of topVouchers Feeds!
.                                                                   1 / 1 (100%)
Time: 1.44 seconds, Memory: 12.00MB
OK (1 test, 1 assertion)

我正在使用以下 Sf4 版本

-------------------- --------------------------------------
Symfony
-------------------- --------------------------------------
Version              4.1.7

服务定义及其默认私有

#config/services.yml
AppServiceFeedGenerator:
arguments:
$feeds: '%feed_generator%'

我认为您不需要再次自动连线。

最新更新