3

我想对command我正在创建的 Symfony 进行功能测试。我Question通过关联个人来利用助手类validator

    $helper = $this->getHelper('question');
    $question = new Question('Enter a valid IP: ');
    $question->setValidator($domainValidator);
    $question->setMaxAttempts(2);

我正在执行的测试是函数式的,所以为了模拟交互,我在 PHPUnit 的测试类中添加了如下内容。这是一段摘录:

public function testBadIpRaisesError()
{
            $question = $this->createMock('Symfony\Component\Console\Helper\QuestionHelper');
            $question
                ->method('ask')
                ->will($this->onConsecutiveCalls(
                    '<IP>',
                    true
                ));
    ...
}

protected function createMock($originalClassName)
{
    return $this->getMockBuilder($originalClassName)
                ->disableOriginalConstructor()
                ->disableOriginalClone()
                ->disableArgumentCloning()
                ->disallowMockingUnknownTypes()
                ->getMock();
}

当然,当我测试超出Question帮助程序的东西时,这个模拟就更好了,但在这种情况下,我想做的是测试整个事情,以确保验证器写得很好。

在这种情况下,最好的选择是什么?对我的验证器进行单元测试是可以的,但我想从用户的角度将其作为黑盒进行功能测试

4

1 回答 1

1

控制台组件CommandTester正好为这个用例提供了一个:https ://symfony.com/doc/current/console.html#testing-commands 。你可能想做这样的事情:

<?php

class ExampleCommandTest extends \PHPUnit\Framework\TestCase
{
    public function testBadIpRaisesError()
    {
        // For a command 'bin/console example'.
        $commandName = 'example';

        // Set up your Application with your command.
        $application = new \Symfony\Component\Console\Application();
        // Here's where you would inject any mocked dependencies as needed.
        $createdCommand = new WhateverCommand();
        $application->add($createdCommand);
        $foundCommand = $application->find($commandName);

        // Create a CommandTester with your Command class processed by your Application.
        $tester = new \Symfony\Component\Console\Tester\CommandTester($foundCommand);

        // Respond "y" to the first prompt (question) when the command is invoked.
        $tester->setInputs(['y']);

        // Execute the command. This example would be the equivalent of
        // 'bin/console example 127.0.0.1 --ipv6=true'
        $tester->execute([
            'command' => $commandName,
            // Arguments as needed.
            'ip-address' => '127.0.0.1',
            // Options as needed.
            '--ipv6' => true,
        ]);
        
        self::assert('Example output', $tester->getDisplay());
        self::assert(0, $tester->getStatusCode());
    }
}

您可以在我正在处理的项目中看到一些更复杂的工作示例:https ://github.com/php-tuf/composer-stager/blob/v0.1.0/tests/Unit/Console/Command/StageCommandTest.php

于 2021-07-01T20:38:27.687 回答