3

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)

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I've used this approach, with all the tests in the base class. It works well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.