简体   繁体   中英

Laravel Mockery - Mocking a class with dependencies injected into constructor

I am trying to mock a class with it's own constructor dependencies. I am using Laravel 5.2.

class A {
    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 am aware that I can change my ClassB.__construct(A $a) to:

  public function __construct(A $a = null) {
    $this->a = $a ?: new A();
  }

But is there a better / cleaner way of doing this? I don't want to change my constructor code just for the sake of unit testing if there is a more acceptable method.

I'm not 100% sure what you want to test, but if you want to mock the class A instance within the B class you can inject a mocked version of A when creating a new instance of B:

$mockA = Mockery::mock('A');
$mockA->shouldReceive('something')->once()->andReturn('Something');

$classBwithMockedA = new B($mockA);

Then you can for instance do (if you want to test the getA-method within the B class):

$this->assertEquals('Something', $classBwithMockedA->getA());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM