36

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?
    }
}
3
  • @james, what is an unit in this case?
    – takeshin
    Jul 15, 2011 at 18:59
  • 2
    This is impossible because you'd need to interject a mock subclass between Parent and Child. Jul 15, 2011 at 20:22
  • i'm thinking i can just modify the child class by wrapping the call to the parent method in some other mockable method.
    – james
    Jul 15, 2011 at 20:42

5 Answers 5

23

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.

8
  • 1
    well you can still mock a sut's own methods, e.g. self mock.
    – james
    Jul 15, 2011 at 20:41
  • @James do you mean Self Shunting?
    – Gordon
    Jul 16, 2011 at 7:55
  • yes, but I am not aware of a way to self shunt a parent method.
    – james
    Jul 17, 2011 at 15:07
  • 12
    Wow, that is wrong on so many levels. Specifically unit testing requires you to mock all used methods of the SUT except for the tested method. There's nothing wrong with extending an object by building upon its existing functionality, and this is when you would legitimately need to call parent methods. Dec 20, 2017 at 15:09
  • 1
    @Sanju if you covered Class A's functionality in the unit test for Class A and the child classes don't modify that functionality, then you don't need to test the inherited functionality.
    – Gordon
    Aug 30, 2020 at 14:16
11

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?
    }
 }
1
  • 14
    the problem with this approach is that you're implementing methods on the child purely for testing purposes, which is not a good approach to development.
    – Oddman
    Aug 11, 2013 at 17:33
3

Here is how I did it, I have no idea if this is correct but it works:

class parentClass {
    public function whatever() {
        $this->doSomething();
    }
}

class childClass extends parentClass {
    public $variable;
    public function subjectUnderTest() {
        $this->variable = 'whocares';
        parent::whatever();
    }
}

now in the test i do:

public function testSubjectUnderTest() {
    $ChildClass = $this->getMock('childClass', array('doSomething'))
    $ChildClass->expects($this->once())
               ->method('doSomething');
    $ChildClass->subjectUnderTest();
    $this->assertEquals('whocares', $ChildClass->variable);
}

what the ?

My reasoning here is that all i really want to test is whether or not my variable got set. i don't really care about what happens in the parent method but since you can't prevent the parent method from being called what i do is mock the dependent methods of the parent method.

now go ahead and tell me i'm wrong :)

3
  • I'd like to know too if this is the best approach, since the legacy project i'm trying to cover does this a lot..
    – qrazi
    Feb 8, 2013 at 12:55
  • 3
    technically you're not mocking the parent method call, so it's not exactly an accurate answer to the original question. What the op needs to do, is mock the whatever() call, not the subsequent call that whatever() itself makes.
    – Oddman
    Aug 11, 2013 at 17:34
  • @Oddman you are partially right, I think Dallas' answer is correct because it is straight to the point (which is to test whatever needs to be tested) i.e. that varable is being set to something in this context May 23, 2017 at 6:08
2

I'm totally agree with @Gordon. I have same issue but I have tried few tricky concept.

My scenario is like

class Parent { // Actual-Parent Class
    function save() {
        // do something
        return $this
    }
}

class Child extends Parent {
   // Subject under test
    function save() {
          // do something
          return parent::save();
    }
}

I have created another parent class with same name "Parent" and treat as a stub and include my stub class(parent) and ignore to actual parent (Actual parent class set into auto-load and stub-parent must be be included )

class Parent { //Stub-Parent class
    function save() {
        return $this
    }
}

Now I create mock object of Child class (via Mock-builder) and complete my test cases with end of assertSame. :-)

$this->assertSame($mock, $mock->save());
3
  • 1
    I don't understand what you mean by "include my stub class(parent) and ignore to actual parent". Could you show how you do this? Apr 3, 2014 at 15:44
  • 1
    This approach can be dangerous. Say you have a class, Parent, that you want to create a hard-coded, manually written mock for, and ignore the real Parent class (just like the given example). PHP could have already, because of an invocation in another class, autoloaded Parent, in which case there will be a fatal "cannot redeclare" error when one attempts to include the fake class. But, danger aside, the way to do it would just be to write a small php file with the fake class defined inside, and manually include that file from the test, so the real class won't have to be autoloaded.
    – russell
    May 6, 2015 at 20:05
  • @dalesikkema : I have already handled it before starting test cases. I have write my own autoloader for test cases. :P Even you can take reference from Joomla github repo May 7, 2015 at 12:18
0

A satisfying solution in my opinion is to create a class that inherits from your class under test and override the implementation of the method you want to give another implementation. This has its flaws: it does not always work, e.g. for already overridden methods and for private methods.

class Parent
{
    function bar()
    {
        echo 'bar';
    }
}

class Child extends Parent
{
    function foo()
    {
        parent::bar();
        echo 'foo';
    }
}

class mockChild extends Child
{
    function bar()
    {
        echo 'baz';
    }
}

class ChildTest extends PHPUnit_TestCase 
{
    function testFoo() {
        $sut = new mockChild();
        $sut->foo();
    }
} 
4
  • This is a pretty old answer, but it should be made clear: this doesn't work. The inheritance chain is Parent > Child > mockChild ... $sut->foo() is calling Child::foo(), which calls parent::bar(), which is obviously its parent, Parent::bar(). The "override" mockChild::bar() is never touched.
    – cautionbug
    Nov 21, 2023 at 1:15
  • Thanks for pointing this out. My PHP skills are quite rusty. Would it work if I change parent:bar() into $this->bar()? Nov 23, 2023 at 10:12
  • It would change it to call the mockChild::bar(), yes. However, the presented problem is how to mock Parent::bar() when Child also defines bar() (rather than foo() in your example). In that situation, you'll have problems with an infinite loop: 3v4l.org/MusWD
    – cautionbug
    Nov 24, 2023 at 22:47
  • I see. That indeed is tricky, I already mentioned in this answer that this solution wouldn't work for already overridden methods. Nov 27, 2023 at 9:48

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.