PHPUnit - Get Started Writing Tests With Assertions
- Unit tests should ideally cover all the possible paths in an application with one unit test covering one specific path in one function or method.
- The tests for a class called
Class
should go into a class calledClassTest
. - Test classes should inherits (most of the time) from
PHPUnit_Framework_TestCase
. - The tests are public methods that are named
test*
. Alternatively, you can use the@test
annotation in a method's docblock to mark it as a test method. - Inside the test methods, assertion methods such as
assertEquals()
are used to assert that an actual value matches an expected value.
Below is an example test class:
<?php
class StackTest extends PHPUnit_Framework_TestCase
{
public function testPushAndPop()
{
$stack = array();
$this->assertEquals(0, count($stack));
array_push($stack, 'foo');
$this->assertEquals('foo', $stack[count($stack)-1]);
$this->assertEquals(1, count($stack));
$this->assertEquals('foo', array_pop($stack));
$this->assertEquals(0, count($stack));
}
}
Assertions
Here are a list of all the assertions that come with PHPunit.
Arrays
- assertArrayHasKey()
- assertArraySubset()
- assertContains()
- assertContainsOnly()
- assertContainsOnlyInstancesOf()
- assertCount()
Booleans
Classes / Objects
- assertInstanceOf()
- assertClassHasAttribute()
- assertClassHasStaticAttribute()
- assertObjectHasAttribute()
Comparison
- assertGreaterThan()
- assertGreaterThanOrEqual()
- assertLessThan()
- assertLessThanOrEqual()
- assertEquals() - asserts the same value (loose typing).
- assertSame() - asserts same type and value.
Files
JSON
Strings
- assertStringMatchesFormat()
- assertStringMatchesFormatFile()
- assertStringEndsWith()
- assertStringEqualsFile()
- assertStringStartsWith()
- assertRegExp()
XML
- assertEqualXMLStructure()
- assertXmlFileEqualsXmlFile()
- assertXmlStringEqualsXmlFile()
- assertXmlStringEqualsXmlString()
Mixed / Misc
Last updated: 1st May 2024
First published: 16th August 2018
First published: 16th August 2018