PHP Unit & Exceptions

Recently I’ve been working on testing some code that throws exceptions. What a pain to test! I thought initially that I had just designed myself into disaster with my new objects. Functions should return results or boolean, right?

Actually, it was easy to switch to using more exceptions than I would have liked in that it was easier to apply DRY principles to the class. Rather than checking the result of a function, it throws an exception. If the object needs to handle it, re-throw the exception to try-catch there.

I’ve seen arguments for doing things either way but I like the way throwing exceptions allows me to pinpoint problems. I realize this isn’t always the case so I’ve organized this particular namespace so that the “manager” of these objects does the trying and catching returning true and false. This allows the consumer to decide whether or not the error or it’s cause is important.

Here’s a sample code of testing exceptions:

public function test_consume()
	try {
	} catch (Exception $e) {

	$this->fail('Expected exception missing: No account found.');

My foray in into PHPUnit has been interesting. I am by no means an expert. What’s nice about this test is that I can use the same test function with the infinite for() loops to test various functionality. Otherwise, I’d have to return() out of each test function adding to how much I have to set up and tear down with each test.

This entry was posted in Uncategorized. Bookmark the permalink.

One Response to PHP Unit & Exceptions