Skip to Main Content
PHPUnit Pocket Guide
book

PHPUnit Pocket Guide

by Sebastian Bergmann
September 2005
Intermediate to advanced content levelIntermediate to advanced
90 pages
1h 53m
English
O'Reilly Media, Inc.
Content preview from PHPUnit Pocket Guide

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering PHP 7

Mastering PHP 7

Branko Ajzele

Publisher Resources

ISBN: 0596101031Errata Page