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

标签 php unit-testing testing phpunit

使用 PHPUnit,有没有办法模拟一个方法并使其表现得像身份 (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'));
    }
}

关于PHPUnit:模拟一种表现得像身份的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33932987/

相关文章:

python - 重新读取打开的文件 Python

testing - cucumber 可以和KIF一起用吗?

php - 电子邮件跟踪 - Apple Mail

javascript - 在不嵌入 php 的情况下保存输入-> 值

c# - Visual Studio Selenium 测试启动本地项目

node.js - Nodejs单元测试策略: check if a table exists and contains the data you expect

php - Laravel DB::statement CREATE DATABASE 无法添加参数(准备语句?)

php - mysqli_use_result()

unit-testing - 如何在 F# 中编写异步单元测试方法

java - 在没有 ArgumentCaptor 的情况下匹配可变对象