Reputation: 510
I have very simple php interface:
interface HasFormattableNumber {
function setNumber();
function setFormat();
function formatNumber();
}
Next, I have many classes implementing this interface. Unfortunately, these classes cannot have a common ancestor (possibly an abstract one which would implement these methods only once). The class basically looks like this:
class A implements HasFormattableNumber {
private $_number;
private $_format;
public function setNumber($n) {
$this->_number = $n;
}
public function setFormat($f) {
$this->_format = $f;
}
public function formatNumber() {
return sprintf($this->_format, $this->_number);
}
}
An unit test would look something like this:
class ATest extends \PHPUnit_Framework_TestCase {
public function testShouldFormatNumber() {
$a = new A();
$a->setNumber(123);
$a->setFormat("xx-%d");
$this->assertEquals("xx-123", $a->formatNumber());
}
}
Is it possible to somehow reuse this test case for all of interface implementations? I know I can copy&paste testShouldFormatNumber() to all of my unit tests, but I prefer keeping it in one place if possible.
Would php Traits help in any way? (I'm not using php 5.4 yet, however)
Upvotes: 3
Views: 1792
Reputation: 2964
You can make a basetest that looks like your ATest except you don't initialize the class A in it, but use a class variable that you will define in all your implementations. You place the file in a directory or with a name so that PHPUnit won't run it. Then in your tests you can inherit from it and create the object as a class variable in setUp().
Upvotes: 5