Posts

Showing posts with the label Unit Testing

Make Your phpUnit Tests Run Faster by Sharing Fixtures

Image
There are few good reasons why you may want to share the fixtures between test, and most of the time the reason could be a bad design. For example, you would like to use share database connections, but your database adapter does not implement Singleton pattern . In order to take advantage of sharing fixtures between tests within single Test Case, your test case should implement two public static methods setUpBeforeClass() and tearDownAfterClass() , and shared fixture itself should be protected static variable. Following example shows sharing database fixture between tests: <?php class DatabaseTest extends PHPUnit_Framework_TestCase { protected static $dbh; public static function setUpBeforeClass() { self::$dbh = new PDO('sqlite::memory:'); } public static function tearDownAfterClass() { self::$dbh = NULL; } public function testShouldReturnCountGreaterThanZero() { $cmd = self::$dbh->prepare('SELEC...

Stubbing and Mocking Static Methods with PHPUnit

Image
PHPUnit has ability to stub and mock static methods. Consider the class Foo : <?php class Foo { public static function doSomething() { return static::helper(); } public static function helper() { return 'foo'; } } ?> To test the static helper() function with PHPUnit, you can write you test like that: <?php class FooTest extends PHPUnit_Framework_TestCase { public function testDoSomething() { $class = $this->getMockClass( 'Foo', /* name of class to mock */ array('helper') /* list of methods to mock */ ); $class::staticExpects($this->any()) ->method('helper') ->will($this->returnValue('bar')); $this->assertEquals( 'bar', $class::doSomething() ); } } ?> The new staticExpects() method works similar to the non-static expects...