php - Laravel Mockery - Mocking a class with dependencies injected into constructor -
i trying mock class it's own constructor dependencies. using laravel 5.2.
class { public function something() {} } class b { protected $a; public function __construct(a $a) { $this->a = $a; } public function geta() { return $this->a->something(); } } mockingtest extends testcase { public function testitgetssomething() { $m = mockery::mock('b'); $m->shouldreceive('geta')->once()->andreturn('something'); } }
i aware can change classb.__construct(a $a)
to:
public function __construct(a $a = null) { $this->a = $a ?: new a(); }
but there better / cleaner way of doing this? don't want change constructor code sake of unit testing if there more acceptable method.
i'm not 100% sure want test, if want mock class instance within b class can inject mocked version of when creating new instance of b:
$mocka = mockery::mock('a'); $mocka->shouldreceive('something')->once()->andreturn('something'); $classbwithmockeda = new b($mocka);
then can instance (if want test geta-method within b class):
$this->assertequals('something', $classbwithmockeda->geta());
Comments
Post a Comment