微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

所以,有点像这样:

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

我想模仿这个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 */]));
    }
}

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

解决方法:

这应该适合你:

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

另外,您可能会发现它很有用(使用onConsecutiveCalls):

http://phpunit.de/manual/3.7/en/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]);
// (...)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐