Pia*_*hal 4 service unit-testing dependency-injection mocking symfony4
我的命令测试有问题。我正在尝试在命令测试中模拟服务,但存在一个问题,即该模拟未在测试中使用。
以下是命令代码:
public function __construct(RpcClient $rpcClient, LoggerInterface $logger, EntityManagerInterface $entityManager)
{
$this->rpcClient = $rpcClient;
$this->logger = $logger;
$this->entityManager = $entityManager;
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$apiSecurityKey = $this->getContainer()->getParameter('api_security_key');
try {
$apiBoxesData = $this->rpcClient->callJsonRPCPostMethod("stations_info", ["apiSecurityKey" => $apiSecurityKey]);
.
.
.
Run Code Online (Sandbox Code Playgroud)
并测试:
//some of dependencies used
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Console\Tester\CommandTester;
class SynchronizeBoxInfoCommandTest extends KernelTestCase
{
const SYNCHRONIZE_BOX_INFO_COMMAND_NAME = "app:synchronize-box-info";
public function setUp()
{
parent::setUp();
static::$kernel = static::createKernel();
static::$kernel->boot();
$application = new Application(static::$kernel);
$this->command = $application->find(self::SYNCHRONIZE_BOX_INFO_COMMAND_NAME);
$this->command->setApplication($application);
$this->commandTester = new CommandTester($this->command);
$this->entityManager = static::$kernel->getContainer()->get('doctrine.orm.entity_manager');
$logger = $this->createMock(LoggerInterface::class);
$this->rpcClientMock = $this->createMock(RpcClient::class);
$application->add(new SynchronizeBoxInfoCommand($this->rpcClientMock, $logger, $this->entityManager));
}
public function testFirstExecutionAllNewData()
{
$this->rpcClientMock->expects($this->once())
->method("callJsonRPCPostMethod")
->willReturn(["test"]);
$this->commandTester->execute([
'command' => $this->command,
]);
}
Run Code Online (Sandbox Code Playgroud)
对于这段代码,当我运行 test, command 时,命令调用方法callJsonRPCPostMethod不会返回模拟字符串“test”,但它会调用方法的实际实现,从而调用 api。我正在搜索整个互联网,实际上没有找到任何适合我的好答案。
我发现在设置结束时将带有模拟服务的命令添加到应用程序中,最终$this->command = $application->find(...)会在模拟服务之前使用命令。因此,在使用要测试的 find 命令之前,您应该使用模拟服务声明命令。下面的代码现在对我有用:
public function setUp()
{
$kernel = self::bootKernel();
$application = new Application($kernel);
$this->entityManager = static::$kernel->getContainer()->get('doctrine.orm.entity_manager');
$logger = $this->createMock(LoggerInterface::class);
$this->rpcClientMock = $this->createMock(RpcClient::class);
$application->add(new SynchronizeBoxInfoCommand($this->rpcClientMock, $logger, $this->entityManager));
$this->command = $application->find(self::SYNCHRONIZE_BOX_INFO_COMMAND_NAME);
$this->commandTester = new CommandTester($this->command);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1198 次 |
| 最近记录: |