我在模拟重载的 __get($index) 方法时遇到问题。 被模拟的类和使用它的被测系统的代码如下:
<?php
class ToBeMocked
{
protected $vars = array();
public function __get($index)
{
if (isset($this->vars[$index])) {
return $this->vars[$index];
} else {
return NULL;
}
}
}
class SUTclass
{
protected $mocky;
public function __construct(ToBeMocked $mocky)
{
$this->mocky = $mocky;
}
public function getSnack()
{
return $this->mocky->snack;
}
}
测试如下:
<?php
class GetSnackTest extends PHPUnit_Framework_TestCase
{
protected $stub;
protected $sut;
public function setUp()
{
$mock = $this->getMockBuilder('ToBeMocked')
->setMethods(array('__get')
->getMock();
$sut = new SUTclass($mock);
}
/**
* @test
*/
public function shouldReturnSnickers()
{
$this->mock->expects($this->once())
->method('__get')
->will($this->returnValue('snickers');
$this->assertEquals('snickers', $this->sut->getSnack());
}
}
真实的代码稍微复杂一点,但并不复杂,因为它的父类中有“getSnacks()”。但这个例子应该足够了。
问题是在使用 PHPUnit 执行测试时出现以下错误:
Fatal error: Method Mock_ToBeMocked_12345672f::__get() must take exactly 1 argument in /usr/share/php/PHPUnit/Framework/MockObject/Generator.php(231)
当我调试时,我什至无法到达测试方法。看起来它在设置模拟对象时中断了。
有什么想法吗?
最佳答案
__get()
接受一个参数,因此您需要为模拟提供一个参数:
/**
* @test
*/
public function shouldReturnSnickers()
{
$this->mock->expects($this->once())
->method('__get')
->with($this->equalTo('snack'))
->will($this->returnValue('snickers'));
$this->assertEquals('snickers', $this->sut->getSnack());
}
with()
方法为 PHPUnit 中的模拟方法设置参数。您可以在Test Doubles部分找到更多详细信息。 .
关于PHPUnit:模拟 __get() 结果为 "__get() must take exactly 1 argument ...",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15110833/