2/07/2011

Verify methods for PHPUnit (like Selenium)

If you have ever used Selenium RC + PHPUnit and used in your tests a lot of verfiy* assertions (i.e. non-strict assertions), you should have seen that they are actually look like:

try {
  $this->assert...();
} catch (PHPUnit_Framework_AssertionFailedError $e) {
  array_push($this->verificationErrors, $e->toString());
}

When you have around 100 verifications the code becomes a mess. That's when you should write your own verify* methods and instead use them.

I thought it would be useful for other PHPUnit + Selenium testers, so here is an example I of verifyEquals() as I guess it's the most used method:

class PHPUnit_Selenium_Verifications extends PHPUnit_Extensions_SeleniumTestCase {

  /**
   * Non-strictly asserts that two variables are equal.
   *
   * @param  mixed   $expected
   * @param  mixed   $actual
   * @param  string  $message
   * @param  float   $delta
   * @param  integer $maxDepth
   * @param  boolean $canonicalize
   * @param  boolean $ignoreCase
   */
  public static function verifyEquals($expected, $actual, $message = '', $delta = 0, $maxDepth = 10, $canonicalize = FALSE, $ignoreCase = FALSE) {
    // try assertion
    try {
      $this->assertEquals($expected, $actual, $message, $delta, $maxDepth, $canonicalize, $ignoreCase);
    // print exception and line number of assertion
    } catch (PHPUnit_Framework_AssertionFailedError $e) {
      array_push($this->verificationErrors, $e->toString(), "  on "  . __LINE__ . " line.");
    }
  }

Now you can just use $this->verifyEquals() instead of try-catch constructions.
I will keep on adding other methods if somebody finds this useful.

UPD: PHPUnit has built-in verifyCommand() method, which resolves all the problems.