PHPUnit:模拟一种表现得像身份的方法

PHPUnit: Mock a method to behave like identity

使用 PHPUnit,是否有任何方法可以模拟一个方法并使其 表现得像 identity (x->x)?围绕 :

的内容
$this->myMethod(Argument::any())->willReturn(<should return the argument untouched>)

您可以使用returnArgument()方法。来自文档:

Sometimes you want to return one of the arguments of a method call (unchanged) as the result of a stubbed method call. Example 9.4 shows how you can achieve this using returnArgument() instead of returnValue().

例如:

class StubTest extends PHPUnit_Framework_TestCase
{
    public function testReturnArgumentStub()
    {
        // Create a stub for the SomeClass class.
        $stub = $this->getMockBuilder('SomeClass')
                     ->getMock();

        // Configure the stub.
        $stub->method('doSomething')
             ->will($this->returnArgument(0));

        // $stub->doSomething('foo') returns 'foo'
        $this->assertEquals('foo', $stub->doSomething('foo'));

        // $stub->doSomething('bar') returns 'bar'
        $this->assertEquals('bar', $stub->doSomething('bar'));
    }
}