doulu4233 2013-04-24 15:08
浏览 30
已采纳

使用at()功能的PHPUNIT模拟工作很奇怪

here is the following code sample

<?php

interface iFS
{
    public function read();
    public function write($data);
}

class MyClass
{
    protected $_fs = null;

    public function __construct(iFS $fs)
    {
        $this->_fs = $fs;
    }

    public function run(array $list)
    {
        foreach ($list as $elm)
        {
            $this->_fs->write($elm);
        }

        return $this->_fs->read();
    }
}

class MyTests extends PHPUnit_Framework_TestCase
{
    public function testFS()
    {
        $mock = $this->getMock('iFS');
        $mock->expects($this->at(0))
                ->method('read')
                ->will($this->returnValue('tototatatiti'));

        $c = new MyClass($mock);
        $result = $c->run(array('toto', 'tata', 'titi'));

        $this->assertEquals('tototatatiti', $result);
    }
}

This is absolutely not a real case but it make happen something strange with phpunit and at($index) feature.

My question is pretty simple, is it normal that the test fails?

I explicitely asked to return "tototatatiti", but it never happens...

When

  • I remove the line $this->_fs->write($elm); or
  • I replace $mock->expects($this->at(0)) by $mock->expects($this->once())

The test pass to green

Is there something I don't understand?

EDIT:

$mock->expects($this->at(3)) ->method('read') ->will($this->returnValue('tototatatiti'));

=> Will make the test pass green...

  • 写回答

2条回答 默认 最新

  • dongshuo6185 2013-04-25 08:43
    关注

    I think the phpunit at() features is not usefull to stub different return result for a mocked method if the mocked object contains some other methods witch are calls too...

    If you want to test something like:

    $stub->expects($this->at(0))
                    ->method('read')
                    ->will($this->returnValue("toto"));
    
    $stub->expects($this->at(1))
                    ->method('read')
                    ->will($this->returnValue("tata"));
    

    You should better use something like

    $stub->expects($this->exactly(2))
                    ->method('read')
                    ->will($this->onConsecutiveCalls("toto", "tata));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大