Removing dependencies in constructor using PHPunit

While trying to get a legacy codebase under testing, I came across an object that does the following:

class Foo
{
    public function __construct($someargs)
    {
        $this->bar = new Bar();
        // [lots more code]
    }
}

      

The bar in this case has a constructor that does some Bad Things, for example. connection to the database. I'm trying to focus on trying out this Foo class so changed it to something like this:

class Foo
{
    public function __construct($someargs)
    {
        $this->bar = $this->getBarInstance();
        // [lots more code]
    }

    protected function getBarInstance()
    {
        return new Bar();
    }
}

      

And tried to test it with the following PHPUnit test:

class FooTest extends PHPUnit_Framework_TestCase
{
    public function testInstance()
    {

        $bar = $this->getMock('Bar');
        $foo = $this->getMock('Foo', array('getBarInstance'));
        $foo->expects($this->any())
            ->method('getBarInstance')
            ->will($this->returnValue($bar));

    }

}

      

However, that won't work - the Foo () constructor is called before my -> expects () is added, so the mocked getBarInstance () method returns zero.

Is there a way to disable this dependency without refactoring the way the constructors use the class?

+2


source to share


1 answer


Use an argument $callOriginalConstructor

getMock()

. Install it on false

. This is the fifth argument to the method. Take a look here: http://www.phpunit.de/manual/current/en/api.html#api.testcase.tables.api



Actually, hold on. Do you want to transfer a fake layout? If you really want it, use the third argument getMock

, which represents the arguments to the constructor. There you can pass mock Bar

to mock Foo

.

+4


source







All Articles