gpt4 book ai didi

phpunit mock 方法多次调用不同参数

转载 作者:IT老高 更新时间:2023-10-28 11:49:41 34 4
gpt4 key购买 nike

有没有办法为不同的输入参数定义不同的模拟期望?例如,我有一个名为 DB 的数据库层类。此类具有称为“Query (string $query)”的方法,该方法在输入时采用 SQL 查询字符串。我可以为这个类(DB)创建模拟并为取决于输入查询字符串的不同查询方法调用设置不同的返回值吗?

最佳答案

如果可以避免使用 at() 并不理想,因为 as their docs claim

The $index parameter for the at() matcher refers to the index, starting at zero, in all method invocations for a given mock object. Exercise caution when using this matcher as it can lead to brittle tests which are too closely tied to specific implementation details.

从 4.1 开始,您可以使用 withConsecutive 例如。

$mock->expects($this->exactly(2))
->method('set')
->withConsecutive(
[$this->equalTo('foo'), $this->greaterThan(0)],
[$this->equalTo('bar'), $this->greaterThan(0)]
);

如果你想让它在连续调用时返回:

  $mock->method('set')
->withConsecutive([$argA1, $argA2], [$argB1], [$argC1, $argC2])
->willReturnOnConsecutiveCalls($retValueA, $retValueB, $retValueC);

关于phpunit mock 方法多次调用不同参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5988616/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com