Base Unit Test Class

Jakobo edited this page Sep 12, 2010 · 2 revisions

Base Class

The absolute minimum needed for a unit test case is a class that implements Snap_RunnableTestCase (and implements the runTests() method). Optionally, a Snap_UnitTestCase can be extended, providing helpful unit test methods. This page assumes you will be extending Snap_UnitTestCase.

// an example of a snap unit test case (the bare minimum)
// Snap_UnitTestCase implements Snap_RunnableTestCase
class My_Class_Under_My_Conditions_Test extends Snap_UnitTestCase {
    public function setUp() {}
    public function tearDown() {}

Required Methods

A functioning UnitTestCase will need to implement the following methods:

  • setUp() – ran before every test method()
  • tearDown() – ran after every test method()
  • runTests() – (from Snap_RunnableTestInterface) runs the tests in the class

In addition, there is any number of test methods in the class. These begin with the word “test” and are the individual tests to run.

Setup and Teardown

The abstract Snap_UnitTestCase class provides a runTests fixture which will run the method setUp() before every test function, and tearDown() at the end of every test function. It’s recommended all variables that were created are destroyed, and the environment is returned as close to default as possible.

  1. testMethod is selected as the next test to run
  2. setUp() is ran
  3. the testMethodName() is ran
  4. tearDown is ran
  5. (1) is repeated with testNextMethod


At the end of every testMethod, a return value is expected or an exception is raised. This return value is created by calling an assertion method that is inherited from Snap_UnitTestCase.

return $this->assertTrue($condition);

A list of full assertions and their usage can be found in the Assertion Reference page.

Knowing You Are Going To (blank)

In a given testMethod, you may find a situation where you know your action will raise an exception, cause a PHP error, or otherwise be incomplete. There is a set of special assertions designed for handling this. They are:

  • $this→willError()
  • $this→willThrow($exception_class)
  • $this→notImplemented()

Info on the usage of these can be found in the Special Assertions page.