In PHPUnit, how do I mock parent methods?

2022-08-30 13:10:45

I want to test a class method that calls upon a parent method with the same name. Is there a way to do this?

class Parent {

    function foo() {
        echo 'bar';
    }
}

class Child {

    function foo() {
            $foo = parent::foo();
            return $foo;
    }
}

class ChildTest extend PHPUnit_TestCase {

    function testFoo() {
        $mock = $this->getMock('Child', array('foo'));

        //how do i mock parent methods and simulate responses?
    }
}

答案 1

You dont mock or stub methods in the Subject-under-Test (SUT). If you feel you have the need to mock or stub a method in the parent of the SUT, it likely means you shouldnt have used inheritance, but aggregation.

You mock dependencies of the Subject-under-Test. That means any other objects the SUT requires to do work.


答案 2

An approach that works to my is the implementation of a wrap to the parent call on the child class, and finally mock those wrap.

You code modified:

class Parent {

    function foo() {
        echo 'bar';
    }
}

class Child {

    function foo() {
            $foo = $this->parentFooCall();
            return $foo;
    }
    function parentFooCall() {
            return parent::foo();
    }
}

class ChildTest extend PHPUnit_TestCase {

    function testFoo() {
        $mock = $this->getMock('Child', array('foo', 'parentFooCall'));

        //how do i mock parent methods and simulate responses?
    }
 }

推荐