PHPSpec: Mocking methods of the object being tested

PHPSpec is very opinionated and won’t let you mock anything of an object being tested. It helps you write better code. This, however, causes issues when you are writing specs for legacy code which (usually) was not well designed.

There is a way you can get around this limitation – a child class. Let’s say the class you want to test is called “Car” and it has a method called “getNumberOfDoors” that you need to mock. Just write a child class and mock the method in it. Here is the code:

Join the Conversation

2 Comments

  1. Shouldn’t this line:
    $this->getNumberOfDoors()->shouldReturn(true);

    Be this:
    $this->isSportsCar()->shouldReturn(true);

Leave a comment

Your email address will not be published. Required fields are marked *