PHPUnit: how do I mock multiple method calls with multiple arguments?(PHPUnit:如何使用多个参数模拟多个方法调用?)
问题描述
我正在为使用 PHPUnit 的方法编写单元测试.我正在测试的方法在同一个对象上调用相同的方法 3 次,但使用不同的参数集.我的问题类似于提出的问题 这里和这里
I am writing a unit test for a method using PHPUnit. The method I am testing makes a call to the same method on the same object 3 times but with different sets of arguments. My question is similar to the questions asked here and here
其他帖子中提出的问题与只接受一个参数的模拟方法有关.
The questions asked in the other posts have to do with mocking methods that only take one argument.
但是,我的方法需要多个参数,我需要这样的东西:
However, my method takes multiple arguments and I need something like this:
$mock->expects($this->exactly(3))
->method('MyMockedMethod')
->with(
$this->logicalOr(
$this->equalTo($arg1, $arg2, arg3....argNb),
$this->equalTo($arg1b, $arg2b, arg3b....argNb),
$this->equalTo($arg1c, $arg2c, arg3c....argNc)
)
);
此代码不起作用,因为 equalTo() 仅验证一个参数.给它多个参数会引发异常:
This code doesn't work because equalTo() validates only one argument. Giving it more than one argument throws an exception:
PHPUnit_Framework_Constraint_IsEqual::__construct() 的参数 #2 必须是数字
Argument #2 of PHPUnit_Framework_Constraint_IsEqual::__construct() must be a numeric
有没有办法为具有多个参数的方法进行 logicalOr 模拟?
Is there a way to do a logicalOr mocking for a method with more than one argument?
提前致谢.
推荐答案
在我的例子中,答案很简单:
In my case the answer turned out to be quite simple:
$this->expects($this->at(0))
->method('write')
->with(/* first set of params */);
$this->expects($this->at(1))
->method('write')
->with(/* second set of params */);
关键是使用$this->at(n),其中n是方法的第N次调用.我尝试过的任何 logicalOr() 变体都无法执行任何操作.
The key is to use $this->at(n), with n being the Nth call of the method. I couldn't do anything with any of the logicalOr() variants I tried.
这篇关于PHPUnit:如何使用多个参数模拟多个方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHPUnit:如何使用多个参数模拟多个方法调用?
基础教程推荐
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何替换eregi() 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
