PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

Testing Traits

Note: This article was originally published at Planet PHP on 12 January 2011.
Planet PHP

The other day I was using the BankAccount sample application during a PHPUnit training. When I showed this code ...


classAResponseAextendsAHashMap
{
AAAA//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:


traitAHashMap
{
AAAAprotectedA$valuesA=Aarray();
A
AAAApublicAfunctionAset($key,A$value)
AAAA{
AAAAAAAA$this-values[$key]A=A$value;
AAAA}
A
AAAApublicAfunctionAget($key)
AAAA{
AAAAAAAAreturnA$this-values[$key];
AAAA}
}
A
classAResponse
{
AAAAuseAHashMap;
A
AAAA//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:


classAHashMapTest

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