如何嘲笑模拟内部方法
How to mockery mock 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);
}
}
结果
Mockery\Exception\InvalidCountException: Method getData() from Mockery_1_ExpWarning should be called
exactly 1 times but called 0 times.
我使用Mockery
作为模拟工具,示例总是关于如何用DI
模拟,我想知道我可以模拟内部方法吗?
您可以使用测试框架的 Partial Mocks features 仅模拟 getData
方法并描述期望。
作为(工作)示例:
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);
}
}
希望对您有所帮助
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
模拟,我想知道我可以模拟内部方法吗?
您可以使用测试框架的 Partial Mocks features 仅模拟 getData
方法并描述期望。
作为(工作)示例:
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);
}
}
希望对您有所帮助