Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock object for a method without dependency injection

I want to test a method of a class that instantiates another object and calls a method of this object.

How can I mock this object and its method Foo2 and run() without dependency injection?

Is this possible or do I need to modify the code for Foo class to inject the object?

class Foo {

    public function bar()
    {
        $foo2 = new Foo2();
        $data = $foo2->run();
    }
}
like image 334
orestiss Avatar asked Oct 30 '22 01:10

orestiss


1 Answers

I recently find a nice features in Mockery (a mock object framework for PHP) called Mocking Hard Dependencies (new Keyword) that permit you to overload/mock class instantiated in a method. As Example:

use Mockery as m;
class BarTest extends \PHPUnit_Framework_TestCase
{
    public function testBar()
    {
        $param = 'Testing';

        $externalMock = m::mock('overload:Foo\Bar2');
        $externalMock->shouldReceive('run')
            ->once()
            ->andReturn('Tested!');

        $foo = new Foo();
        $foo->bar();
    }
}

Hope this help

like image 122
Matteo Avatar answered Nov 10 '22 13:11

Matteo