You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHPUnit 5.7中方法两次调用的单元测试编写问题

我来帮你搞定这个PHPUnit 5.7的测试问题~你的getData方法里两次调用findCustomers,要验证这两次调用的参数和次数,有两种很实用的写法,都适配你的版本:

方法一:使用at()指定调用顺序

at($index)可以精准指定方法的第几次调用(索引从0开始),适合需要明确区分每一次调用逻辑的场景:

/**
 * @covers \Model\Controller\CustomersController::getData()
 */
public function testGetData() {
    // 初始化模拟的返回实体(根据你的实际需求调整)
    $mockCustomerEntity = new \Model\Entity\CustomersEntity();

    // 验证第一次调用findCustomers(索引0)
    $this->customerController->expects($this->at(0))
        ->method('findCustomers')
        ->with(['idCustomer' => 1], 0, 0, null)
        ->willReturn($mockCustomerEntity);

    // 验证第二次调用findCustomers(索引1)
    $this->customerController->expects($this->at(1))
        ->method('findCustomers')
        ->with([], 0, 0, null)
        ->willReturn($mockCustomerEntity); // 这里可以返回和第一次不同的实体,如果需要的话

    // 调用被测方法,传入对应参数(确保urlPathParams是[1],和预期的idCustomer匹配)
    $result = $this->customerController->getData(0, 0, null, [1]);

    // 可选:根据实际业务断言返回结果
    // $this->assertEquals(预期值, $result);
}

方法二:使用withConsecutive()批量验证多次调用

这种写法更简洁,通过exactly(2)指定方法被调用恰好两次,再用withConsecutive()批量定义每一次的参数,willReturnOnConsecutiveCalls()对应每一次的返回值:

/**
 * @covers \Model\Controller\CustomersController::getData()
 */
public function testGetData() {
    $mockCustomerEntity = new \Model\Entity\CustomersEntity();

    $this->customerController->expects($this->exactly(2))
        ->method('findCustomers')
        ->withConsecutive(
            // 第一次调用的参数列表
            [['idCustomer' => 1], 0, 0, null],
            // 第二次调用的参数列表
            [[], 0, 0, null]
        )
        ->willReturnOnConsecutiveCalls(
            $mockCustomerEntity, // 第一次调用的返回值
            $mockCustomerEntity  // 第二次调用的返回值,可按需修改
        );

    // 调用被测方法
    $result = $this->customerController->getData(0, 0, null, [1]);

    // 可选:断言返回结果
}

注意事项

  • 确保你传给getData的参数和测试中预期的一致,比如$urlPathParams传[1],才能让$idCustomer等于1,和with()里的参数匹配。
  • 如果两次调用的返回值不同,直接在willReturnOnConsecutiveCalls()里传入不同的实体即可。

内容的提问来源于stack exchange,提问作者fatma_wings

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:14:01