PHPUnit:如何使用多个参数模拟多个方法调用?

PHPUnit: how do I mock multiple method calls with multiple arguments?(PHPUnit:如何使用多个参数模拟多个方法调用?)
本文介绍了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:如何使用多个参数模拟多个方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)