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

2022-01-08 00:00:00 mocking unit-testing php phpunit

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

I've got a PHPUnit mock object that returns 'return value' no matter what its arguments:

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

我希望能够根据传递给模拟方法的参数返回不同的值.我尝试过类似的方法:

What I want to be able to do is return a different value based on the arguments passed to the mock method. I've tried something like:

$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"'));

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

But this causes PHPUnit to complain if the mock isn't called with the argument 'two', so I assume that the definition of methodToMock('two') overwrites the definition of the first.

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

So my question is: Is there any way to get a PHPUnit mock object to return a different value based on its arguments? And if so, how?

推荐答案

使用回调.例如(直接来自 PHPUnit 文档):

Use a callback. e.g. (straight from PHPUnit documentation):

<?php
class StubTest extends PHPUnit_Framework_TestCase
{
    public function testReturnCallbackStub()
    {
        $stub = $this->getMock(
          'SomeClass', array('doSomething')
        );

        $stub->expects($this->any())
             ->method('doSomething')
             ->will($this->returnCallback('callback'));

        // $stub->doSomething() returns callback(...)
    }
}

function callback() {
    $args = func_get_args();
    // ...
}
?>

在 callback() 中做任何你想做的处理,并根据你的 $args 适当地返回结果.

Do whatever processing you want in the callback() and return the result based on your $args as appropriate.

相关文章