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

How can I get PHPUnit MockObjects to return different values based on a parameter?(如何让 PHPUnit MockObjects 根据参数返回不同的值?)
本文介绍了如何让 PHPUnit MockObjects 根据参数返回不同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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.

这篇关于如何让 PHPUnit MockObjects 根据参数返回不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)