Sunday 21 October 2012

SimpleTest CheatSheet

PHP Unit Testing with SimpleTest

Following on from my getting up & running with SimpleTest I thought it would be good to give you guys a list of the assertions you will become all too familiar with.. very soon :D

So, There are a variety of different assertions

All of these functions are contained in unit_tester.php

assertTrue(x)
Fail if x is false
assertFalse(x)
Fail if x is true
assertNull(x)
Fail if x is set
assertNotNull(x)
Fail if x not set
assertIsA(x, t)
Fail if x is not the class or type t
assertEqual(x, y)
Fail if x y is false
assertNotEqual(x, y)
Fail if x y is true
assertIdentical(x, y)
Fail if x === y is false
assertNotIdentical(x, y)
Fail if x === y is true
assertReference(x, y)
Fail unless x and y are the same variable
assertCopy(x, y)
Fail if x and y are the same variable
assertWantedPattern(p, x)
Fail unless the regex p matches x
assertNoUnwantedPattern(p, x)
Fail if the regex p matches x
assertNoErrors()
Fail if any PHP error occoured
assertError(x)
Fail if no PHP error or incorrect message

Encapsulating Tests

When needing to do some work before and after every test, SimpleTest has setUp() and tearDown() methods which are run before and after every test respectively.
Convenience methods for debugging code or Extending the suite

pass()
Sends a test pass
fail()
Sends a test failure
error()
Sends an exception event
signal($type, $payload)
Sends a user defined message to the test reporter
dump($var)
Does a formatted print_r() for quick and dirty debugging

To get you started. Here is a standard unit test class called UnitTestCase. That can be used as a super class also.

Mocks as actors

set return values simulate connection

Mocks as critics

expect results
expect($method, $args)
Arguments must match if called
expectAt($timing, $method, $args)
Arguments must match when called on the $timing'th time
expectCallCount($method, $count)
The method must be called exactly this many times
expectMaximumCallCount($method, $count)
Call this method no more than $count times
expectMinimumCallCount($method, $count)
Must be called at least $count times
expectNever($method)
Must never be called
expectOnce($method, $args)
Must be called once and with the expected arguments if supplied
expectAtLeastOnce($method, $args)
Must be called at least once, and always with any expected arguments

And that it. Have fun! :)