Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test multiple class with same PHPUnit test case

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)

like image 328
Ludeks Avatar asked Jan 29 '26 11:01

Ludeks


1 Answers

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().

like image 65
Clarence Avatar answered Jan 31 '26 00:01

Clarence



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!