Class Testme
{
public function testMe ($input, &$output)
{
$output = 9;
}
}
正如大家所见,此方法修改输入参数。现在该如何嘲笑它?像模仿返回值
之类的东西$mock = $this->getMock ('Testme');
$mock = $this->expects ($this->once())->with (1, 0)->will
这里写什么来修改第二个参数?我希望第二个参数为10。
答案 0 :(得分:2)
$mock = $this->getMock('Testme');
$mock->expects($this->once())
->method('testMe')
->with(1, 0)
->will(
$this->returnCallback(
function ($input, &$output) {
$output = 10;
}
)
);
但要注意!它仍然无法工作,导致两次通话(问题:https://github.com/sebastianbergmann/phpunit-mock-objects/issues/181)
您可以使用此解决方案解决此问题:https://github.com/sebastianbergmann/phpunit-mock-objects/issues/181#issuecomment-52289669
答案 1 :(得分:2)
不幸的是,如果你使用PHPUnit Mock Objects,这是不可能的。 See known issue #81 "Arguments that are passed by reference are not handled properly
我建议改用Prophecy。默认情况下,PHPUnit> = 4.5将支持预言。同时你可以包括phpspec / prophecy-phpunit,它在PHPUnit中集成了预言。
这是Prophecy的一个用例:
namespace SchlimmerFinger;
use Prophecy\PhpUnit\ProphecyTestCase;
class MockWithReferenceTest extends ProphecyTestCase
{
public function testShouldChangeValue()
{
$foo = $this->prophesize(__NAMESPACE__ . '\\Foo');
$a = 20;
$b = 35;
$c = 22;
$foo->bar($a, $b, $c)->will(function(array $arguments) use (&$b){
$arguments[1] = $b = 10;
return array_sum($arguments);
});
self::assertEquals(52, $foo->reveal()->bar($a, $b, $c));
self::assertEquals(10, $b);
}
}
class Foo
{
public function bar($a, &$b, $c)
{
}
}