Testing Traits
The other day I was using the BankAccount sample application during a PHPUnit training. When I showed this code ...
classA ResponseA extendsA HashMap
{
A A A A //A ...
}
?
... one of the developers said: "That is wrong! A Response is not a HashMap. You should use delegation instead." And, of course, he was right. I replied with "Actually, what we want to do here (once we have PHP 5.4) is to use traits."
I went ahead and refactored the code:
traitA HashMap
{
A A A A protectedA $valuesA =A array();
A
A A A A publicA functionA set($key,A $value)
A A A A {
A A A A A A A A $this-values[$key]A =A $value;
A A A A }
A
A A A A publicA functionA get($key)
A A A A {
A A A A A A A A returnA $this-values[$key];
A A A A }
}
A
classA Response
{
A A A A useA HashMap;
A
A A A A //A ...
}
?
To make sure that I did not break anything, I ran the test suite for the BankAccount sample application. The tests for classes that previously extended HashMap (Response, for instance) still passed. Of course, the tests for HashMap were now broken because trait cannot be instantiated.
Suddenly I had to think about making traits testable. This is what I came up with:
classA HashMapTest
Truncated by Planet PHP, read more at the original (another 4796 bytes)


