KnpLabs / ConsoleServiceProvider

A Console service provider for Silex
MIT License
107 stars 37 forks source link

Please document how do test for a command #14

Closed desarrolla2 closed 7 years ago

desarrolla2 commented 9 years ago

Or provide example here and i will send PR to update README.md

dominics commented 7 years ago

I typically do something like this: https://gist.github.com/dominics/8e6fd3142cd3da72f57c9c9b5346db5a

It's a 'functional' test, as it extends WebTestCase and requires instantiating the Silex\Application.

This approach is similar to this article (from 2011!): http://alexandre-salome.fr/blog/Test-your-commands-in-Symfony2 - the only ConsoleServiceProvider-specific trick is dispatching a ConsoleEvents::INIT yourself, if you'd like all the commands registered for your test. (You could also just register the Command under test.)

skalpa commented 7 years ago

How to test Symfony commands is documented here.

If your command doesn't use any of the Knp\Console\Application methods, you may be able to use the CommandTester helper. Otherwise, you can use the ApplicationTester:

<?php

use My\Command\MyCommand;
use Symfony\Component\Console\Tester\ApplicationTester;

class MyCommandTest extends \PHPUnit_Framework_TestCase
{
    public function testOutput()
    {
        $app = new \Silex\Application();
        $app->register(new \Knp\Provider\ConsoleServiceProvider(), [
            'console.name' => 'app',
            'console.version' => '1.0',
            'console.project_directory' => __DIR__,
        ]);
        $console = $app['console'];
        $console->setAutoExit(false);
        $console->add(new MyCommand());

        $tester = new ApplicationTester($console);
        // Replace this will the real arguments/options you want to pass
        $tester->run(['my:command']);

        $this->assertContains('Some text', $tester->getDisplay());
    }
}
skalpa commented 7 years ago

There is now a page documenting how to use the CommandTester class with the console provider.