How to test parent call method in a class for phpspec?

Member

by gilbert , in category: PHP General , 8 months ago

How to test parent call method in a class for phpspec?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , 8 months ago

@gilbert 

To test a parent call method in a class using phpspec, you can follow these steps:

  1. First, make sure that your class extends the parent class that contains the method you want to test.
  2. In your spec file for your class, create a new method to test the parent call.
  3. Use the getParentBehavior() method from the phpspec ObjectBehavior class to create a mock object of the parent class.
  4. Set up any necessary expectations on the mock object, such as method calls or return values.
  5. Call the method on your class that eventually calls the parent method.
  6. Use the shouldHaveReceived() method on the mock object to assert that the parent method was called with the expected arguments.


Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
use MyNamespaceMyClass;
use ParentNamespaceParentClass;

class MyClassSpec extends ObjectBehavior
{
    function it_calls_parent_method()
    {
        $parentMock = $this->getParentBehavior(ParentClass::class)->getMock();
        $this->beAnInstanceOf(MyClass::class, [$parentMock]);

        // Set up expectations on the mock object
        $parentMock->methodToTest()->shouldBeCalled();

        // Call the method on the class that calls the parent method
        $this->methodToTest();

        // Assert that the parent method was called with the expected arguments
        $parentMock->shouldHaveReceived('methodToTest');
    }
}


In this example, we create a mock object of the parent class using getParentBehavior() and set up an expectation on the methodToTest() method. Then, we call the method on our class that eventually calls the parent method, and finally assert that the parent method was called with the expected arguments using shouldHaveReceived().