如何模拟mock内部方法

时间:2015-09-22 04:19:58

标签: php unit-testing phpunit mockery

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);
    }
}

结果

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

我使用Mockery作为模拟工具,示例总是关于如何使用DI进行模拟,我想知道我可以模拟内部方法吗?

1 个答案:

答案 0 :(得分:3)

您可以使用测试框架的Partial Mocks features仅模拟getData方法并描述期望。

As(工作)示例:

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);
    }
}

希望这个帮助