How to mock an internal method

Target.php

<?php

class Target
{
    public function validate()
    {
        $this->getData();
        return true;
    }

    public function getData()
    {
        return array();
    }
}

TargetTest.php

<?php

class TargetTest extends PHPUnit_Framework_TestCase
{
    public function testValidate()
    {
        $mock = m::mock('Target');
        $mock->shouldReceive('getData')
            ->once();
        $expected = $this->exp->validate();

        $this->assertTrue($expected);
    }
}

result

Mockery\Exception\InvalidCountException: Method getData() from Mockery_1_ExpWarning should be called exactly 1 times but called 0 times.

I use Mockeryas a mock, an example is always about how to mock with DI, I would like to know if I can mock an internal method?

+4
source share
1 answer

You can use the Partial Mocks functions of the testing framework for the mock method only getDataand describe the expectation.

Like (working) Example:

use Mockery as m;

class TargetTest extends \PHPUnit_Framework_TestCase
{
    public function testValidate()
    {
        $mock = m::mock('Target[getData]');
        $mock->shouldReceive('getData')
            ->once();
        $expected = $mock->validate();

        $this->assertTrue($expected);
    }
}

Hope for this help

+3
source

Source: https://habr.com/ru/post/1608415/


All Articles