On Github saem / presentation-2013-04-29-phpunit
Created by Saem Ghani / @saemg
Your journey starts and ends here
use PHPUnit_Framework_TestCase; class HelloWorldTest extends PHPUnit_Framework_TestCase { /** * @test */ public function sayHello() { $g = new Greeter(); $this->assertEquals("Hello, World!", $g->greet()); } }Notice the grammar. I assume an autoloader and some sort of bootstrapping
class FooerTest extends PHPUnit_Framework_TestCase { protected function setUp() { $this->fooer = new Fooer() } protected function tearDown() { $this->fooer->shutdown(); } public function testHowAFooerFoos() { /* import test code */ } }
class FooerTest extends PHPUnit_Framework_TestCase { /** * @test * @dataProvider myDataProvider */ public function fuzzTestFooer($input, $expected) { /* ... setup code ... */ $this->assertEquals($expected, $fooer->foo($data)); } public function myDataProvider() { return [ ['a', 0], ['b', 1], /* ... */ ]; } }
/** * @test */ public function whenPassedBadInputAnInvalidArgumentExceptionIsThrown() { $this->setExpectedException('InvalidArgumentException', 'Optionally, test message'); /* ... Code that throws an exception ... */ }PHPUnit convers PHP errors to exceptions so test them that way
/** * @test */ public function importantSpecThatNeedsToBeImplemented() { $this->markTestIncomplete // can also skip tests }PHPUnit convers PHP errors to exceptions so test them that way
class Fooer { public function __construct($logger) { /* ... */ } public function foo() { /* ... */ $isLogged = $this->logger->log('I foo\'d.'); /* ... */ } } class FooerTest extends PHPUnit_Framework_TestCase { public function aFooerLogsEverytimeItFoos() { $logger = $this->getMock('Logger'); $fooer = new Fooer($logger); $logger->expects($this->once()) ->method('log') ->with($this->equalTo('I foo\'d.')) ->will($this->returnValue(true)); $fooer->foo(); } }
<?xml version="1.0" encoding="UTF-8"?> <!-- http://www.phpunit.de/manual/current/en/appendixes.configuration.html --> <phpunit backupGlobals = "false" backupStaticAttributes = "false" colors = "true" convertErrorsToExceptions = "true" convertNoticesToExceptions = "true" convertWarningsToExceptions = "true" processIsolation = "false" stopOnFailure = "false" syntaxCheck = "false" bootstrap = "bootstrap.php" > <testsuites> <testsuite name="Project Test Suite"> <directory>../src/Tests</directory> </testsuite> </testsuites> </phpunit>
$> phpunit -c phpunit.xml