Skip to content

Instantly share code, notes, and snippets.

@dominics
Created March 29, 2017 04:41
Show Gist options
  • Save dominics/8e6fd3142cd3da72f57c9c9b5346db5a to your computer and use it in GitHub Desktop.
Save dominics/8e6fd3142cd3da72f57c9c9b5346db5a to your computer and use it in GitHub Desktop.
Testing a Knp ConsoleServiceProvider Command
<?php
namespace MyApp\Test;
use Knp\Console\ConsoleEvent;
use Knp\Console\ConsoleEvents;
use Silex\Application;
use Knp\Console\Application as ConsoleApplication;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Output\BufferedOutput;
/**
* Command test base class
*
* Used for tests of Command classes
*/
abstract class CommandTestCase extends WebTestCase
{
/**
* Runs the specified console command and returns the output
*
* @param string $command Command and arguments specified as a single string
* @return string The output of the command
*/
protected function runCommand(string $command): string
{
$input = new StringInput($command);
$output = new BufferedOutput();
$application = $this->getConsoleApplication($this->createApplication());
$application->run($input, $output);
return $output->fetch();
}
/**
* Creates a ConsoleApplication
*
* @param Application $app
* @return ConsoleApplication
*/
protected function getConsoleApplication(Application $app): ConsoleApplication
{
$application = new ConsoleApplication(
$app,
__DIR__ . '/../../..',
'MyApp',
'0.0.1'
);
$application->setAutoExit(false);
$this->registerCommands($app, $application);
return $application;
}
/**
* Register commands on the console application
*
* Uses the typical INIT event to register commands the normal way. You could also override this method if you
* want to test Commands in isolation (call $application->add() yourself)
*
* @param Application $app
* @param ConsoleApplication $application
*/
protected function registerCommands(Application $app, ConsoleApplication $application)
{
$app['dispatcher']->dispatch(ConsoleEvents::INIT, new ConsoleEvent($application));
}
}
<?php
namespace MyApp\Something;
use MyApp\Test\CommandTestCase;
class SomethingTest extends CommandTestCase
{
public function testWithSomeArguments()
{
$output = $this->runCommand('some:command --with-args');
$this->assertStringStartsWith('Hello, world!', $output);
}
}
@dominics
Copy link
Author

The MyApp\Test\WebTestCase that is being extended by the CommandTestCase is just a simple implementation of Silex\WebTestCase (i.e. it defines createApplication(): Silex\Application)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment