O'Reilly logo

PHPUnit Pocket Guide by Sebastian Bergmann

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

PHPUnit2_Framework_Assert

Most test cases written for PHPUnit are derived indirectly from the class PHPUnit2_Framework_Assert, which contains methods for automatically checking values and reporting discrepancies. The methods are declared static, so you can write design-by-contract style assertions in your methods and have them reported through PHPUnit (Example 19).

Example 19. Design-by-contract style assertions

<?php
require_once 'PHPUnit2/Framework/Assert.php';

class Sample {
  public function aSampleMethod($object) {
    PHPUnit2_Framework_Assert::assertNotNull($object);
  }
}
$sample = new Sample;
$sample->aSampleMethod(NULL);
?>
Fatal error: Uncaught exception
  'PHPUnit2_Framework_AssertionFailedError'
with message 'expected: <NOT NULL> but was: <NULL>'

Most of the time, though, you'll be checking the assertions inside of tests.

There are two variants of each of the assertion methods: one takes a message to be displayed with the error as a parameter, and one does not. Example 20 demonstrates an assertion method with a message. The optional message is typically displayed when a failure is displayed, which can make debugging easier.

Example 20. Using assertions with messages

<?php
require_once 'PHPUnit2/Framework/TestCase.php';
class MessageTest extends PHPUnit2_Framework_TestCase {
  public function testMessage( ) {
    $this->assertTrue(FALSE, 'This is a custom message.');
  }
}
?>

The following example shows the output you get when you run the testMessage( ) test from Example 20, using assertions ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required