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();
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With