I would like to use PHP’s assert function in my unit testing framework. It has the advantage of being able to see the expression being evaluated (including comments) within the error message.
The problem is that each method containing tests may have more than one assert statement, and I would like to keep track of how many actual assert statements have been run. assert does not give me a way to count how many times it has been run, only how many times it has failed (within the failure callback).
I tried to abstract the assert statement into a function so that I can add a counting mechanism.
private function assertTrue($expression) {
$this->testCount++;
assert($expression);
}
This does not work however because any variables within the expression are now out of scope.
$var = true;
$this->assertTrue('$var == true'); // fails
Any advice on how I can use assert in my unit testing while being able to count the number of actual tests?
The two ideas I have come up with are to make users count themselves
$this->testCount++;
assert('$foo');
$this->testCount++;
assert('$bar');
or make users put only one assert in each test method (I could then count the number of methods run). but neither of these solutions is very enforcable, and make coding more difficult. Any ideas on how to accomplish this? Or should I just strip assert() from my testing framework?
You are restricted by the fact
assert()must be called in the same scope the variables you are testing lie. That leaves — as far as I can tell — solutions that require extra code, modify the source before runtime (preprocessing), or a solution that extends PHP at the C-level. This is my proposed solution that involves extra code.Downfalls to this approach: all variables used in unit testing must be declared as
$v->*rather than$*, whereas variables written in the assert statement are still written as$*. Secondly, the warning emitted byassert()will not report the line number at which$this->assert()was called.For more consistency you could move the
assert()method to the variable holder class, as that way you could think about each unit test operating on a test bed, rather than having some sort of magical assert call.