News Archive
PhpRiot Newsletter
Your Email Address:

More information

expected exceptions annotations, mocked object calls, oh my.

Note: This article was originally published at Planet PHP on 25 December 2010.
Planet PHP

Note: I have tested this in PHPUnit 3.4.1 and haven't tried it out in 3.5.
Anyone who has worked with PHPUnit has most likely worked with expected exceptions and mock objects. The nice thing about working with expected exceptions is that we have access to a handy @expectedException annotation. I've gotten into the habit of using this for exceptions my fixtures should throw but also for when I'm using a mock object to verify a method call. So my tests usually expect foo_exception for fixture throws and when i'm testing method calls via a mock, they expect Exception. Therein lies my problem. Because all my custom class exceptions obviously extend the Exception class, I can get some false positives in testing.

equire_once 'Zend/Loader/Autoloader.php'; $loader = Zend_Loader_Autoloader::getInstance(); require_once('foo.php'); class tmpTest extends PHPUnit_Framework_Testcase { A /** * @expectedException Exception */ public function testFooBar() { $foo=new foo(); $foo-bar(); } A /** * @expectedException Exception */ public function testBarBaz() { $mock=$this-getMock('foo',array('baz')); $mock-expects($this-any()) -method('baz') -will($this-throwException(new Exception('baz'))); $mock-barbaz(); } "/

Truncated by Planet PHP, read more at the original (another 4157 bytes)