热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

PHPUnit:验证该数组是否具有给定值的键-PHPUnit:Verifyingthatarrayhasakeywithgivenvalue

Giventhefollowingclass:鉴于以下课程:<?phpclassExample{private$Other;publicfunctio

Given the following class:

鉴于以下课程:

Other = $Other;
    }

    public function query ()
    {   
        $params = array(
            'key1' => 'Value 1'
            , 'key2' => 'Value 2'
        );

        $this->Other->post($params);
    }
}

And this testcase:

而这个测试用例:

getMock('Other', array('post'));

        $Mock->expects($this->once())
              ->method('post')
              ->with(YOUR_IDEA_HERE);

        $Example = new Example($Mock);
        $Example->query();
    }

How do I verify that $params (which is an array) and is passed to $Other->post() contains a key named 'key1' that has a value of 'Value 1'?

如何验证$ params(这是一个数组)并传递给$ Other-> post()包含一个名为'key1'的键,其值为'Value 1'?

I do not want to verify all of the array - this is just a sample code, in actual code the passed array has a lot more values, I want to verify just a single key/value pair in there.

我不想验证所有的数组 - 这只是一个示例代码,在实际代码中传递的数组有更多的值,我想在那里只验证一个键/值对。

There is $this->arrayHasKey('keyname') that I can use to verify that the key exists.

我可以使用$ this-> arrayHasKey('keyname')来验证密钥是否存在。

There is also $this->contains('Value 1'), which can be used to verify that the array has this value.

还有$ this-> contains('Value 1'),可用于验证数组是否具有此值。

I could even combine those two with $this->logicalAnd. But this of course does not give the desired result.

我甚至可以将这两个与$ this-> logicalAnd结合起来。但这当然不会产生预期的结果。

So far I have been using returnCallback, capturing the whole $params and then doing asserts on that, but is there perhaps another way to do what I want?

到目前为止,我一直在使用returnCallback,捕获整个$ params,然后对此进行断言,但是有没有其他方法可以做我想要的?

5 个解决方案

#1


32  

The $this->arrayHasKey('keyname'); method exists but its name is assertArrayHasKey :

$ this-> arrayHasKey('keyname');方法存在,但其名称为assertArrayHasKey:

// In your PHPUnit test method
$hi = array(
    'fr' => 'Bonjour',
    'en' => 'Hello'
);

$this->assertArrayHasKey('en', $hi);    // Succeeds
$this->assertArrayHasKey('de', $hi);    // Fails

#2


15  

In lieu of creating a re-usable constraint class, I was able to assert an array key's value using the existing callback constraint in PHPUnit. In my use case, I needed to check for an array value in the second argument to a mocked method (MongoCollection::ensureIndex(), if anyone is curious). Here's what I came up with:

代替创建可重用的约束类,我能够使用PHPUnit中的现有回调约束来声明数组键的值。在我的用例中,我需要在模拟方法的第二个参数中检查数组值(MongoCollection :: ensureIndex(),如果有人好奇的话)。这就是我想出的:

$mockedObject->expects($this->once())
    ->method('mockedMethod')
    ->with($this->anything(), $this->callback(function($o) {
        return isset($o['timeout']) && $o['timeout'] === 10000;
    }));

The callback constraint expects a callable in its constructor, and simply invokes it during evaluation. The assertion passes or fails based on whether the callable returns true or false.

回调约束期望在其构造函数中使用callable,并在评估期间简单地调用它。断言根据callable是返回true还是false来传递或失败。

For a large project, I'd certainly recommend creating a re-usable constraint (as in the above solution) or petitioning for PR #312 to be merged into PHPUnit, but this did the trick for a one-time need. It's easy to see how the callback constraint might be useful for more complicated assertions, too.

对于一个大型项目,我当然建议创建一个可重用的约束(如上面的解决方案)或请求将PR#312合并到PHPUnit中,但这样做可以满足一次性需求。很容易看出回调约束对于更复杂的断言是如何有用的。

#3


8  

I ended up creating my own constraint class, based on the attribute one

我最终创建了自己的约束类,基于属性1

cOnstraint= $constraint;
        $this->arrayKey    = $arrayKey;
    }


    /**
     * Evaluates the constraint for parameter $other. Returns TRUE if the
     * constraint is met, FALSE otherwise.
     *
     * @param mixed $other Value or object to evaluate.
     * @return bool
     */
    public function evaluate($other)
    {
        if (!array_key_exists($this->arrayKey, $other)) {
            return false;
        }

        $this->value = $other[$this->arrayKey];

        return $this->constraint->evaluate($other[$this->arrayKey]);
    }

    /**
     * @param   mixed   $other The value passed to evaluate() which failed the
     *                         constraint check.
     * @param   string  $description A string with extra description of what was
     *                               going on while the evaluation failed.
     * @param   boolean $not Flag to indicate negation.
     * @throws  PHPUnit_Framework_ExpectationFailedException
     */
    public function fail($other, $description, $not = FALSE)
    {
        parent::fail($other[$this->arrayKey], $description, $not);
    }


    /**
     * Returns a string representation of the constraint.
     *
     * @return string
     */
    public function toString ()
    {
        return 'the value of key "' . $this->arrayKey . '"(' . $this->value . ') ' .  $this->constraint->toString();
    }


    /**
     * Counts the number of constraint elements.
     *
     * @return integer
     */
    public function count ()
    {
        return count($this->constraint) + 1;
    }


    protected function customFailureDescription ($other, $description, $not)
    {
        return sprintf('Failed asserting that %s.', $this->toString());
    }

It can be used like this:

它可以像这样使用:

 ... ->with(new Test_Constraint_ArrayHas($this->equalTo($value), $key));

#4


2  

In case you wish to do some complex testing on the parameter, and also have useful messages and comparisons, there is always the option of placing assertions within the callback.

如果您希望对参数进行一些复杂的测试,并且还有有用的消息和比较,总是可以选择在回调中放置断言。

e.g.

例如

$clientMock->expects($this->once())->method('post')->with($this->callback(function($input) {
    $this->assertNotEmpty($input['txn_id']);
    unset($input['txn_id']);
    $this->assertEquals($input, array(
        //...
    ));
    return true;
}));

Notice that the callback returns true. Otherwise, it would always fail.

请注意,回调返回true。否则,它总会失败。

#5


-3  

Sorry, I'm not an English speaker.

对不起,我不是说英语的人。

I think that you can test if a key exists in the array with the array_key_exists function, and you can test if the value exists with array_search

我认为您可以使用array_key_exists函数测试数组中是否存在键,并且您可以使用array_search测试该值是否存在

For example:

例如:

function checkKeyAndValueExists($key,$value,$arr){
    return array_key_exists($key, $arr) && array_search($value,$arr)!==false;
}

Use !== because array_search return the key of that value if exists and it may be 0.

使用!==因为如果存在,array_search将返回该值的键,它可能为0。


推荐阅读
  • Go Cobra命令行工具入门教程
    本文介绍了Go语言实现的命令行工具Cobra的基本概念、安装方法和入门实践。Cobra被广泛应用于各种项目中,如Kubernetes、Hugo和Github CLI等。通过使用Cobra,我们可以快速创建命令行工具,适用于写测试脚本和各种服务的Admin CLI。文章还通过一个简单的demo演示了Cobra的使用方法。 ... [详细]
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • 本文讨论了在Windows 8上安装gvim中插件时出现的错误加载问题。作者将EasyMotion插件放在了正确的位置,但加载时却出现了错误。作者提供了下载链接和之前放置插件的位置,并列出了出现的错误信息。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • 本文介绍了九度OnlineJudge中的1002题目“Grading”的解决方法。该题目要求设计一个公平的评分过程,将每个考题分配给3个独立的专家,如果他们的评分不一致,则需要请一位裁判做出最终决定。文章详细描述了评分规则,并给出了解决该问题的程序。 ... [详细]
  • 本文讨论了使用差分约束系统求解House Man跳跃问题的思路与方法。给定一组不同高度,要求从最低点跳跃到最高点,每次跳跃的距离不超过D,并且不能改变给定的顺序。通过建立差分约束系统,将问题转化为图的建立和查询距离的问题。文章详细介绍了建立约束条件的方法,并使用SPFA算法判环并输出结果。同时还讨论了建边方向和跳跃顺序的关系。 ... [详细]
  • 从零学Java(10)之方法详解,喷打野你真的没我6!
    本文介绍了从零学Java系列中的第10篇文章,详解了Java中的方法。同时讨论了打野过程中喷打野的影响,以及金色打野刀对经济的增加和线上队友经济的影响。指出喷打野会导致线上经济的消减和影响队伍的团结。 ... [详细]
  • 开发笔记:实验7的文件读写操作
    本文介绍了使用C++的ofstream和ifstream类进行文件读写操作的方法,包括创建文件、写入文件和读取文件的过程。同时还介绍了如何判断文件是否成功打开和关闭文件的方法。通过本文的学习,读者可以了解如何在C++中进行文件读写操作。 ... [详细]
  • 本文讨论了在openwrt-17.01版本中,mt7628设备上初始化启动时eth0的mac地址总是随机生成的问题。每次随机生成的eth0的mac地址都会写到/sys/class/net/eth0/address目录下,而openwrt-17.01原版的SDK会根据随机生成的eth0的mac地址再生成eth0.1、eth0.2等,生成后的mac地址会保存在/etc/config/network下。 ... [详细]
  • 本文讨论了在手机移动端如何使用HTML5和JavaScript实现视频上传并压缩视频质量,或者降低手机摄像头拍摄质量的问题。作者指出HTML5和JavaScript无法直接压缩视频,只能通过将视频传送到服务器端由后端进行压缩。对于控制相机拍摄质量,只有使用JAVA编写Android客户端才能实现压缩。此外,作者还解释了在交作业时使用zip格式压缩包导致CSS文件和图片音乐丢失的原因,并提供了解决方法。最后,作者还介绍了一个用于处理图片的类,可以实现图片剪裁处理和生成缩略图的功能。 ... [详细]
  • IOS开发之短信发送与拨打电话的方法详解
    本文详细介绍了在IOS开发中实现短信发送和拨打电话的两种方式,一种是使用系统底层发送,虽然无法自定义短信内容和返回原应用,但是简单方便;另一种是使用第三方框架发送,需要导入MessageUI头文件,并遵守MFMessageComposeViewControllerDelegate协议,可以实现自定义短信内容和返回原应用的功能。 ... [详细]
  • 本文讨论了编写可保护的代码的重要性,包括提高代码的可读性、可调试性和直观性。同时介绍了优化代码的方法,如代码格式化、解释函数和提炼函数等。还提到了一些常见的坏代码味道,如不规范的命名、重复代码、过长的函数和参数列表等。最后,介绍了如何处理数据泥团和进行函数重构,以提高代码质量和可维护性。 ... [详细]
  • Ihaveaworkfolderdirectory.我有一个工作文件夹目录。holderDir.glob(*)>holder[ProjectOne, ... [详细]
  • 使用C++编写程序实现增加或删除桌面的右键列表项
    本文介绍了使用C++编写程序实现增加或删除桌面的右键列表项的方法。首先通过操作注册表来实现增加或删除右键列表项的目的,然后使用管理注册表的函数来编写程序。文章详细介绍了使用的五种函数:RegCreateKey、RegSetValueEx、RegOpenKeyEx、RegDeleteKey和RegCloseKey,并给出了增加一项的函数写法。通过本文的方法,可以方便地自定义桌面的右键列表项。 ... [详细]
  • Problemexplanation: ... [详细]
author-avatar
布瓜Pourqu2502854853
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有