PHPUnit:模拟一个接受参数的方法

r.b*_*gil 5 php phpunit unit-testing

我正在为一个接收"搜索"类的类创建测试,该类使用搜索字符串搜索超市并且具有返回相应项的方法"getItem($ itemNo)".

所以,有点像这样:

class MyClass 
{
    public function __construct(Search $search) {
        $item0 = $search->getItem(0);
        $item1 = $search->getItem(1);
        // etc... you get the picture
    }
}
Run Code Online (Sandbox Code Playgroud)

我想模仿这个Search类,因为我不想每次进行测试时搜索超市.

所以我写了:

class MyClassTest extends PHPUnit_Framework_TestCase 
{
    public function setUp()
    {
        $searchResults=$this->getMockBuilder('Search')
                            //Because the constructor takes in a search string:
                            ->disableOriginalConstructor() 
                            ->getMock();

        $pseudoSupermarketItem=array( "SearchResult1", "SearchResult2", etc...);

        $this->searchResult
               ->expects($this->any())
               ->method('getItem')
               ->with(/*WHAT DO I PUT HERE SO THAT THE METHOD WILL TAKE IN A NUMBER*/)
               ->will($this->returnValue($pseudoSupermarketItem[/* THE NUMBER THAT WAS PUT IN */]));
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您在代码中看到的,我希望mock方法接受一个整数,如MyClass中所示,然后返回相应的pseudoSupermarketItem字符串.到目前为止,我不确定如何实现这一点,任何帮助表示赞赏!

Cyp*_*ian 5

这应该为您工作:

$this->searchResult
    ->expects($this->any())
    ->method('getItem')
    ->with($this->isType('integer'))
    ->will($this->returnCallback(function($argument) use ($pseudoSupermarketItem) {
        return $pseudoSupermarketItem[$argument];
    });
Run Code Online (Sandbox Code Playgroud)

另外,也许您会发现它有用(使用onConsecutiveCalls):

http://phpunit.de/manual/3.7/zh-CN/test-doubles.html#test-doubles.stubs.examples.StubTest7.php

第三种方式是这样的:

$this->searchResult
    ->expects($this->at(0))
    ->method('getItem')
    ->with($this->equalTo(0))
    ->will($this->returnValue($pseudoSupermarketItem[0]);
$this->searchResult
    ->expects($this->at(1))
    ->method('getItem')
    ->with($this->equalTo(1))
    ->will($this->returnValue($pseudoSupermarketItem[1]);
// (...)
Run Code Online (Sandbox Code Playgroud)