Skip to content

Instantly share code, notes, and snippets.

@tommy-muehle
Last active September 18, 2017 09:45
Show Gist options
  • Save tommy-muehle/8ae2809832bb443c243961a005ec66b3 to your computer and use it in GitHub Desktop.
Save tommy-muehle/8ae2809832bb443c243961a005ec66b3 to your computer and use it in GitHub Desktop.
Gist's for better testing article
<?php
namespace My\App;
class CacheWarmer
{
private $cacheDirectory;
public function __construct(string $cacheDirectory)
{
$this->cacheDirectory = $cacheDirectory;
}
public function warmUp()
{
if (!is_dir($this->cacheDirectory) &&!mkdir($this->cacheDirectory)) {
throw new \RuntimeException('Could not create cache directory!');
}
// ...
}
}
<?php
namespace My\App\Tests;
use My\App\CacheWarmer;
use org\bovigo\vfs\vfsStream;
class CacheWarmerTest extends \PHPUnit_Framework_TestCase
{
private $root;
public function setUp()
{
$this->root = vfsStream::setup();
}
/**
* @test
*/
public function canCreateCacheDirectoryOnWarmUp()
{
$cacheWarmer = new CacheWarmer($this->root->url() . '/cache');
$cacheWarmer->warmUp();
$this->assertTrue($this->root->hasChild('cache'));
}
}
<?php
namespace My\App;
class PdfCreator
{
// ...
public function execute(string $htmlFile, string $pdfFile)
{
$output = [];
$returnValue = 0;
exec(sprintf('/usr/bin/wkhtmltopdf %s %s', $htmlFile, $pdfFile), $output, $returnValue);
if ($returnValue !== 0) {
throw new \RuntimeException('Could not create PDF file!');
}
return $output;
}
// ...
}
<?php
namespace My\App\Tests;
use My\App\PdfCreator;
class PdfCreatorTest extends \PHPUnit_Framework_TestCase
{
use \phpmock\phpunit\PHPMock;
/**
* @test
* @expectedException \RuntimeException
*/
public function executeReturnsAnExceptionOnFailure()
{
$exec = $this->getFunctionMock('My\App', 'exec');
$exec->expects($this->once())->willReturnCallback(
function ($command, &$output, &$returnValue) {
$this->assertEquals('/usr/bin/wkhtmltopdf file.html file.pdf', $command);
$output = ['failure'];
$returnValue = 1;
}
);
$pdfCreator = new PdfCreator;
$pdfCreator->execute('file.html', 'file.pdf');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment