Assertions within PHPUnit SetUp/ TearDown

PHPUnit includes setUp() and tearDown() methods which are called for each test method. These are used to create pre-conditions for test methods or set up external resources used by each test.

It’s useful to note that assertions can be called within these methods to test if they have worked correctly, for example creating and then removing some database settings:

public function setUp()
{
	$this->db->set( 'foo', 'foo' );

	$this->db->set( 'bar', 'bar' );

	$this->assertSame( 2, $this->db->count() );
}



public function tearDown()
{
	$this->db->delete( 'foo' );

	$this->db->delete( 'bar' );

	$this->assertSame( 0, $this->options->count() );
}

Of course, if the assertions fail they’ll be repeated for every test method, but that’s probably better than wasting time investigating why tests are failing when it is¬†setUp() that is the problem.

They can also be used to¬†ensure that the tearDown() method has worked and doesn’t leave something persistent to interfere with subsequent tests.