Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to proxy to original methods and disable the constructor at the same time with Phpunit?

Tags:

php

phpunit

Using Phpunit 4.5.2, I'm trying to mock the following class:

class Foo {
    public function bar() {}
}

class MyClass
{
    private $foo;

    public function __construct(Foo $foo) {
        $this->foo = $foo;
        //some other stuff that I want to suppress during the unit tests.
    }

    public function doSomething() {
        $this->foo->bar();
    }
}

I wish to achieve the following:

  1. Have the mock call the original methods.
  2. Avoid the constructor (I'm setting the foo property using reflection).

This code:

$mock = $this->getMockBuilder('MyClass')
             ->disableOriginalConstructor()
             ->enableProxyingToOriginalMethods()
             ->getMock()

Will fail with the following error message:

Argument 1 passed to MyClass::__construct() must be an instance of Foo, none given

If I remove the enableProxyingToOriginalMethods(), the mock is created without errors, so it seems that when I enable proxying, this enables the constructor despite the disableOriginalConstructor() call.

How can I enable proxying while keeping the constructor disabled?

like image 885
Marc Puts Avatar asked Sep 25 '14 12:09

Marc Puts


1 Answers

If you proxy to the original class then an object of the original class must be instantiated. If the original class has a constructor then that constructor must be executed. Hence disableOriginalConstructor() and enableProxyingToOriginalMethods() are mutually exclusive.

Feel free to open a ticket at https://github.com/sebastianbergmann/phpunit-mock-objects/issues to ask for PHPUnit to issue an error when these two are used together.

like image 107
Sebastian Bergmann Avatar answered Oct 20 '22 02:10

Sebastian Bergmann