mercredi 28 octobre 2015

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')
        ->disableOriginalConstructor()
        ->getMock();

    $this->fruitSalad->addFruit($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?

Aucun commentaire:

Enregistrer un commentaire