PHPUnit使用willReturnOnConsecutiveCalls调用同一方法两次,结果为空数据

kninwzqo  于 2023-09-29  发布在  PHP
关注(0)|答案(1)|浏览(115)

**问题:**如何测试同一个方法(getNextUniqueBunch),结果却不一样?

function exampleQuestion() {
  $rows = [];
  $rowsAgain = [];

  while ($bunch = $this->_dataSourceModel->getNextUniqueBunch()) {
            $rows[] = $bunch;
  }

  //Some changes done and now getNextUniqueBunch will return a different result

  while ($bunch = $this->_dataSourceModel->getNextUniqueBunch()) {
            $rowsAgain[] = $bunch;
  }
}

方案一

public function importDataProvider(): array
{
    return [
        [
            [
                '_email' => '[email protected]',
                '_website' => 'base',
                '_store'=> 'admin',
                '_entity_id' => 'abc'
            ]
        ],
        [
            [
                '_email' => '[email protected]',
                '_store' => 'admin',
                '_entity_id' => 'abc'
            ]
        ]
    ];
}

   /**
     * @dataProvider importDataProvider
     * @return void
     */
    public function testImportData($data)
    {
        $this->dataSourceModel->expects($this->any())
            ->method('getNextUniqueBunch')
            ->withConsecutive([], [])
            ->willReturnOnConsecutiveCalls([$data], [$data]);
       $mockClassObj->exampleQuestion(); 
    }

在这个解决方案中,第一次调用getNextUniqueBunch将返回一个数组,但在第二次调用getNextUniqueBunch时,它返回一个空数组

方案二:如果我们将代码更改为

$this->dataSourceModel->expects($this->at(3))
            ->method('getNextUniqueBunch')
            ->withConsecutive([], [])
            ->willReturnOnConsecutiveCalls([$data], [$data]);

在本例中,我们使用了已弃用的**$this->at(3)**,但它可以工作,并为第二次getNextUniqueBunch调用返回数据
什么是正确的方法来实现-相同的方法调用不同的结果?我搜索和调查了很多,但没有一个对我有用。

gg58donl

gg58donl1#

我们需要添加null,以便跳转到下一个相同的方法while循环,例如

$this->dataSourceModel->expects($this->any())
            ->method('getNextUniqueBunch')
            ->willReturnOnConsecutiveCalls(
                ['_email' => '[email protected]'],
                ['_website' => 'base'],
                ['_store'=> 'admin'],
                ['_entity_id' => 'abc'],
                null,
                ['_email' => '[email protected]'],
                ['_store' => 'admin'],
                ['_entity_id' => 'abc']
            );

相关问题