我有一个带抽象保护方法的抽象基类
abstract class AbstractSample
{
abstract protected function getConnection();
}
和子类,其中protected方法被重新定义为public:
class ConcreteSample extends AbstractSample
{
public function getConnection()
{
return 'connection resource';
}
}
这是我要测试的课程:
class Caller
{
protected $_sample;
public function __construct(ConcreteSample $sample)
{
$this->_sample = $sample;
}
public function method()
{
$conn = $this->_sample->getConnection();
return $conn;
}
}
和测试单元本身:
class Sample_Test extends \PHPUnit_Framework_TestCase
{
public function test_getConnection()
{
$RESOURCE = 'mocked resource';
$mSample = \Mockery::mock(ConcreteSample::class);
$mSample
->shouldReceive('getConnection')->once()
->andReturn($RESOURCE);
$obj = new Caller($mSample);
$res = $obj->method();
$this->assertEquals($RESOURCE, $res);
}
}
当我运行测试时出现错误:
InvalidArgumentException : getConnection() cannot be mocked as it a protected method and mocking protected methods is not allowed for this mock
/.../vendor/mockery/mockery/library/Mockery.php:670
/.../vendor/mockery/mockery/library/Mockery.php:678
/.../vendor/mockery/mockery/library/Mockery.php:629
/.../var/tmp/Sample_Test.php:13
如何模拟在基类中重新定义受保护方法的公共方法? Mockery版本是0.9.4
答案 0 :(得分:1)
你可以试试这个:
$mSample = \Mockery::mock(ConcreteSample::class)
->shouldAllowMockingProtectedMethods();