PHPUnit mock class that has named static constructor

Given I have a FruitSalad class (the system under test):

class FruitSalad
    protected $fruits = [];

    public function addFruit(Fruit $fruit)
        $this->fruits[] = $fruit;
        return $this;

And I have a Fruit class:

class Fruit
    public static function withName($name)
        $instance = new MyDependencyClass();
        $instance->name = $name;
        return $instance;

A trivial example, however you can see that the Fruit class uses a named static constructor, and the addFruit() method on the FruitSalad class type hints Fruit as its expected parameter.

When writing a test for addFruit(), I need to mock the Fruit class.

function test_it_can_add_a_fruit_to_its_list_of_fruits()
    $fruit = $this->getMockBuilder('Fruit')

    // Do some assertion.

This creates a simple mock of the Fruit class, but I want to instantiate it via the withName() static method – and I do not want to expose a setter for the name property.

How can I create a mock for Fruit using the static named constructor?


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s