PHPUnit:如何模拟具有多个参数的多个方法调用? [英] PHPUnit: how do I mock multiple method calls with multiple arguments?

查看:70
本文介绍了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:如何模拟具有多个参数的多个方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆