Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PHPUnit, how do I mock parent methods?

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?     } } 
like image 464
james Avatar asked Jul 15 '11 18:07

james


People also ask

Which method is used to create a mock with PHPUnit?

PHPUnit provides methods that are used to automatically create objects that will replace the original object in our test. createMock($type) and getMockBuilder($type) methods are used to create mock object. The createMock method immediately returns a mock object of the specified type.

What is stub in PHPUnit?

Stub. Stubs are used with query like methods - methods that return things, but it's not important if they're actually called. $stub = $this->createMock(SomeClass::class); $stub->method('getSomething') ->willReturn('foo'); $sut->action($stub);


1 Answers

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.

like image 177
Gordon Avatar answered Oct 06 '22 13:10

Gordon