I have a custom console command that extends Drupal\Console\Command\ContainerAwareCommand. Inside the command I need to access the container to fetch a service. But now I'm struggling with figuring out how to mock the return value from the container->get command so that I can inject a stub of the actual service the command uses. So how do I set up the unit test?

The code inside the execute() method of my command that somehow needs to be stubbed:

$importer = $this

The unit test class so far looks like this:

namespace Drupal\my_module\Tests\Command\Calendar;

use Drupal\Console\Application;
use Drupal\my_module\Command\ImportCalendarEventsCommand;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\Console\Tester\CommandTester;

class ImportCalendarEventsCommandTest extends UnitTestCase

protected $command;
protected $application;

public function setUp()

    $helperSetStub = $this->getMock('Symfony\Component\Console\Helper\HelperSet');

    $this->command = new ImportCalendarEventsCommand($helperSetStub);

    $this->application = new Application(array('container' => $this->getContainerStub()));

public function tearDown()

public function testItIsAContainerAwareCommand()
    $this->assertInstanceOf('Drupal\Console\Command\ContainerAwareCommand', $this->command);
    $this->assertEquals('fmo:calendar:import', $this->command->getName());

 * @param [string] arg [description]
public function testCanImportCalendarEvents()

    $command = $this->application->find('fmo:calendar:import');
    $commandTester = new CommandTester($command);

    $code = $commandTester->execute(
        ['interactive' => false]

    $this->assertEquals(0, $code);


private function getContainerStub()
    $stub = $this


    return $stub;

But this does not work. There are new dependencies I need to mock. I tried looking through the test folder of the Drupal Console project itself, but could not find any tests for the ContainerAwareCommand in that project either...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.