PHP and assertions

Posted on 04.11.2010 by Antti Holvikari

I want to make Sham itself to throw Exceptions. Currently you need to use whatever testing framework you are using for asserting. This means that for example with PHPUnit your assertions will look something like this:

$this->assertTrue($stub->calls('method', 'param 1')->once());

This is too verbose.

To integrate with PHPUnit correctly I would need to throw PHPUnit_Framework_AssertionFailedError exceptions. This would make Sham assertions report correctly as failures, and not as errors. However, I don’t want to integrate only with PHPUnit, I want Sham to be as simple and generic as possible.

What we need is an AssertionException class in PHP’s itself. This small addition would make testing tools play nicely together. PHPUnit would extend AssertionException and so would Sham. We would all have the same meaning for a failing test.

This kind of thing would be easy to implement in PHP, but as far as I know there is no way of implementing anything in PHP that would be included in PHP. That is, all the SPL classes are implemented in C.

Assert

Taking this a bit further, there should also be something in PHP that would throw these AssertionErrors. For this I propose the assert keyword. The assert statement would look like this:

assert <expression>;

If the expression evaluates to false, an AssertionException would be thrown.

Yes, there’s assert(), the function, but it’s hideous.

Maybe I’ll pick up my dusty Extending and Embedding PHP someday and whip up a patch. Until then, any takers?

blog comments powered by Disqus