简体   繁体   中英

PHP Unit Test Mocking a member variable dependency

Hello lets say I want to test the function run from Class A and I'm using Mockery to mock external dependencies:

class A {
    protected myB;

    public function __construct(B $param) {
      $this->myB = $param;
    }

    protected function doStuff() {
      return "done";
    }

    public function run() {
      $this->doStuff();

      $this->myB->doOtherStuff();

      return "finished";
    }
}

class B {
    public function doOtherStuff() {
      return "done";
    }
}

So I wrote the test like this:

public function testRun() {
    $mockB = Mockery::mock('overload:B');
    $mockB->shouldReceive('doOtherStuff')
        ->andReturn("not done");

    $mockA = Mockery::mock(A::class)->makePartial()->shouldAllowMockingProtectedMethods();
    $mockA->shouldReceive('doStuff')->andReturns("done");
    
    $mockA->run();
}

This throws me an exception like this: Error: Call to a member function doStuff() on null

I tried diffrent variations of mocking the internal dependency B which is getting called in the run function but I always endend up in an exception.

What am I doing wrong here?

Don't mock the thing you are testing. Inject the mocked B into A .

    public function testRun()
    {
        // Arrange
        $mockB = Mockery::mock(B::class);
        $a = new A($mockB);

        // Assert
        $mockB->shouldReceive('doOtherStuff')
            ->once()
            ->andReturn("not done");

        // Act
        $a->run();
    }

If you want to monkey patch A , you can still pass the mocked B in ( more details: constructor arguments in mockery ):

    public function testRun()
    {
        // Arrange
        $mockB = Mockery::mock(B::class);
        $a     = Mockery::mock(A::class, [$mockB])
            ->makePartial()
            ->shouldAllowMockingProtectedMethods();
        $a->shouldReceive('doStuff')
            ->andReturns('mocked done');

        // Assert
        $mockB->shouldReceive('doOtherStuff')
            ->once()
            ->andReturn('not done');

        // Act
        $a->run();
    }

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