154

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

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

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

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

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

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

4

11 回答 11

134

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

<?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 返回结果。

于 2008-11-15T11:13:17.827 回答
125

来自最新的 phpUnit 文档:“有时,存根方法应根据预定义的参数列表返回不同的值。您可以使用returnValueMap()创建将参数与相应返回值相关联的映射。”

$mock->expects($this->any())
    ->method('getConfigValue')
    ->will(
        $this->returnValueMap(
            array(
                array('firstparam', 'secondparam', 'retval'),
                array('modes', 'foo', array('Array', 'of', 'modes'))
            )
        )
    );
于 2012-07-31T09:27:47.723 回答
54

我有一个类似的问题(虽然略有不同......我不需要基于参数的不同返回值,但必须测试以确保将 2 组参数传递给同一个函数)。我偶然发现使用这样的东西:

$mock = $this->getMock();
$mock->expects($this->at(0))
    ->method('foo')
    ->with(...)
    ->will($this->returnValue(...));

$mock->expects($this->at(1))
    ->method('foo')
    ->with(...)
    ->will($this->returnValue(...));

它并不完美,因为它要求 2 次调用 foo() 的顺序是已知的,但实际上这可能还不错

于 2010-01-13T08:53:34.943 回答
30

您可能希望以 OOP 方式进行回调:

<?php
class StubTest extends PHPUnit_Framework_TestCase
{
    public function testReturnAction()
    {
        $object = $this->getMock('class_name', array('method_to_mock'));
        $object->expects($this->any())
            ->method('method_to_mock')
            ->will($this->returnCallback(array($this, 'returnTestDataCallback')));

        $object->returnAction('param1');
        // assert what param1 should return here

        $object->returnAction('param2');
        // assert what param2 should return here
    }
    
    public function returnTestDataCallback()
    {
        $args = func_get_args();

        // process $args[0] here and return the data you want to mock
        return 'The parameter was ' . $args[0];
    }
}
?>
于 2011-01-12T00:01:45.323 回答
21

这并不完全符合您的要求,但在某些情况下它可以提供帮助:

$mock->expects( $this->any() ) )
 ->method( 'methodToMock' )
 ->will( $this->onConsecutiveCalls( 'one', 'two' ) );

onConsecutiveCalls - 按指定顺序返回值列表

于 2014-03-19T10:51:41.010 回答
7

传递两级数组,其中每个元素是一个数组:

  • 首先是方法参数,最后是返回值。

例子:

->willReturnMap([
    ['firstArg', 'secondArg', 'returnValue']
])
于 2017-04-04T13:02:44.307 回答
3

您还可以按如下方式返回参数:

$stub = $this->getMock(
  'SomeClass', array('doSomething')
);

$stub->expects($this->any())
     ->method('doSomething')
     ->will($this->returnArgument(0));

正如您在Mocking 文档中所见,该方法returnValue($index)允许返回给定的参数。

于 2013-08-06T08:59:43.217 回答
0

你的意思是这样的吗?

public function TestSomeCondition($condition){
  $mockObj = $this->getMockObject();
  $mockObj->setReturnValue('yourMethod',$condition);
}
于 2008-11-10T14:25:19.337 回答
0

我有一个类似的问题,我也无法解决(关于 PHPUnit 的信息非常少)。就我而言,我只是将每个测试单独测试 - 已知输入和已知输出。我意识到我不需要制作一个万事通的模拟对象,我只需要一个用于特定测试的特定对象,因此我将测试分开,并且可以单独测试我的代码的各个方面单元。我不确定这是否适用于您,但这取决于您需要测试的内容。

于 2008-11-10T15:13:04.950 回答
-1
$this->BusinessMock = $this->createMock('AppBundle\Entity\Business');

    public function testBusiness()
    {
        /*
            onConcecutiveCalls : Whether you want that the Stub returns differents values when it will be called .
        */
        $this->BusinessMock ->method('getEmployees')
                                ->will($this->onConsecutiveCalls(
                                            $this->returnArgument(0),
                                            $this->returnValue('employee')                                      
                                            )
                                      );
        // first call

        $this->assertInstanceOf( //$this->returnArgument(0),
                'argument',
                $this->BusinessMock->getEmployees()
                );
       // second call


        $this->assertEquals('employee',$this->BusinessMock->getEmployees()) 
      //$this->returnValue('employee'),


    }
于 2017-05-09T15:13:50.130 回答
-2

尝试 :

->with($this->equalTo('one'),$this->equalTo('two))->will($this->returnValue('return value'));
于 2009-10-03T21:26:30.617 回答