John Smith
John Smith

Reputation: 6207

Php, how to mock object instantiation?

So, a function:

function testMe ($a, $b)
{
    $obj = new CalculationObject();
    return $obj->calcIt ($a, $b);
}

how to mock this creation?

Upvotes: 1

Views: 847

Answers (1)

Fabian Schmengler
Fabian Schmengler

Reputation: 24576

Refactor the function to separate object creation and object usage.

If this is a method of a class, the trivial solution is to make $obj a class property so you can replace it with a mock.

If you always need a new instance of CalculationObject, the factory pattern can be used.

Example:

function testMe ($a, $b)
{
    $obj = $this->factory->getNewCalculationObject();
    return $obj->calcIt ($a, $b);
}

Then replace $this->factory with a stub that returns your mock for getNewCalculationObject().

If this is really a procedural function, not a method, you need to pass the dependency to the function:

function testMe ($a, $b, $factory)
{
    $obj = $factory->getNewCalculationObject();
    return $obj->calcIt ($a, $b);
}

You could use the normal factory by default to make it backwards compatible to your current implementation:

function testMe ($a, $b, $factory = null)
{
    if ($factory === null) {
        $factory = new CalculationObjectFactory();
    }
    $obj = $factory->getNewCalculationObject();
    return $obj->calcIt ($a, $b);
}

If this looks a bit clumsy to you, consider moving the function into a class.

Upvotes: 5

Related Questions