Monday, October 3, 2011

Unit Testing in PHP

I'm currently working with PHP. I found this bit of code in one of the unit testing tools for PHP. It's not terrible, but it's not great either. To me, it represents one of the tipping points for the value proposition of unit testing in the first place: Having solid unit-test coverage of code should also mean that we can take an extra few minutes to fix it.

public function appendValue($value)
{
   if (is_null($value))
   {
      $this->append('null');
   }
   elseif (is_string($value))
   {
      $this->_toPhpSyntax($value);
   }
   elseif (is_float($value))
   {
      $this->append('<');
      $this->append($value);
      $this->append('F>');
   }
   elseif (is_bool($value))
   {
      $this->append('<');       
      $this->append($value ? 'true' : 'false');
      $this->append('>');
   }
   elseif (is_array($value) || $value instanceof Iterator || $value instanceof IteratorAggregate)
   {
      $this->appendValueList('[', ', ', ']', $value);
   }
   elseif (is_object($value) && !method_exists($value, '__toString'))
   {
      $this->append('<');       
      $this->append(get_class($value));
      $this->append('>');
   }
   else
   {
      $this->append('<');       
      $this->append($value);
      $this->append('>');
   }
   return $this;
}