Skip to content

Instantly share code, notes, and snippets.

@EwanValentine
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EwanValentine/1c53c5f8a0851f05211c to your computer and use it in GitHub Desktop.
Save EwanValentine/1c53c5f8a0851f05211c to your computer and use it in GitHub Desktop.
Symfony2 command unit test helper class.
<?php
namespace Ladbible\BaseBundle\Tests\Command;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Output\StreamOutput;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Bundle\FrameworkBundle\Console\Application;
/**
* AbstractCommandTestHelper
*
* @author Ewan Valentine <ewan@theladbible.com>
* @copyright 65Twenty 2015
*/
abstract class AbstractCommandTestHelper extends WebTestCase
{
/**
* runCommand
*
* Creates instance of Application in
* test mode and allows commands to be
* ran.
*
* @param Client $client
* @param string $command
*
* @return mixed
*/
public function runCommand(Client $client, $command)
{
// Create separate instance of application kernel
$application = new Application($client->getKernel());
// Set auto exit application to false
$application->setAutoExit(false);
// Create a temporary file to contain command output
$fp = tmpfile();
// Command input
$input = new StringInput($command);
// Stream output to temporary file
$output = new StreamOutput($fp);
// Run command
$application->run($input, $output);
// Finds first byte in temporary file
fseek($fp, 0);
// Resets output
$output = '';
// Iterates through 'til end of temporary file
while (!feof($fp)) {
$output = fread($fp, 4096);
}
// Closes file stream
fclose($fp);
// Returns final output
return $output;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment