beT*_*iba 12 php phpunit overloading built-in
我在模拟重载的__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;
}
}
Run Code Online (Sandbox Code Playgroud)
测试看起来如下:
<?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());
}
}
Run Code Online (Sandbox Code Playgroud)
真正的代码有点复杂,虽然不是很多,在其父类中有"getSnacks()".但这个例子应该足够了.
问题是我在使用PHPUnit执行测试时遇到以下错误:
Fatal error: Method Mock_ToBeMocked_12345672f::__get() must take exactly 1 argument in /usr/share/php/PHPUnit/Framework/MockObject/Generator.php(231)
Run Code Online (Sandbox Code Playgroud)
当我调试时,我甚至无法达到测试方法.它似乎在设置模拟对象时中断.
有任何想法吗?
__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());
}
Run Code Online (Sandbox Code Playgroud)
该with()方法为 PHPUnit 中的模拟方法设置参数。您可以在测试替身部分找到更多详细信息。