相关疑难解决方法(0)

如何让PHPUnit MockObjects根据参数返回不同的值?

我有一个PHPUnit模拟对象,'return value'无论它的参数是什么都返回:

// From inside a test...
$mock = $this->getMock('myObject', 'methodToMock');
$mock->expects($this->any))
     ->method('methodToMock')
     ->will($this->returnValue('return value'));
Run Code Online (Sandbox Code Playgroud)

我想要做的是根据传递给mock方法的参数返回一个不同的值.我尝试过类似的东西:

$mock = $this->getMock('myObject', 'methodToMock');

// methodToMock('one')
$mock->expects($this->any))
     ->method('methodToMock')
     ->with($this->equalTo('one'))
     ->will($this->returnValue('method called with argument "one"'));

// methodToMock('two')
$mock->expects($this->any))
     ->method('methodToMock')
     ->with($this->equalTo('two'))
     ->will($this->returnValue('method called with argument "two"'));
Run Code Online (Sandbox Code Playgroud)

但是如果没有使用参数调用mock,这会导致PHPUnit抱怨'two',所以我假设定义methodToMock('two')覆盖了第一个的定义.

所以我的问题是:有没有办法让PHPUnit模拟对象根据其参数返回不同的值?如果是这样,怎么样?

php phpunit unit-testing mocking

128
推荐指数
7
解决办法
7万
查看次数

标签 统计

mocking ×1

php ×1

phpunit ×1

unit-testing ×1