在PHPUnit中测试迭代 [英] Testing iterables in PHPUnit

查看:135
本文介绍了在PHPUnit中测试迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHPUnit中,很容易断言两个数组包含相同的值:

In PHPUnit it quite easy to assert that two arrays contain the same value:

 $this->assertEquals( [1, 2, 3], [1, 2, 3] );

PHP的最新版本使迭代器和生成器的使用更具吸引力,并且PHP 7.1引入了可迭代的伪类型。这意味着我可以编写函数来获取并返回 iterable ,而不会绑定到我使用普通旧的数组或使用惰性生成器

Recent versions of PHP made usage of Iterators and Generators a lot more attractive, and PHP 7.1 introduced the iterable pseudo-type. That means I can write functions to take and return iterable without binding to the fact I am using a plain old array or using a lazy Generator.

如何断言返回的函数的返回值可迭代?理想情况下,我可以做类似

How do I assert the return value of functions returning an iterable? Ideally I could do something like

 $this->assertIterablesEqual( ['expected', 'values'], $iterable );

有没有这样的功能?或者,是否有一种理智的测试方法,不需要在我的测试中添加一堆额外的命令式代码?

Is there such a function? Alternatively, is there a sane way of testing this that does not involve adding a pile of besides-the-point imperative code to my tests?

推荐答案

我认为你需要首先包装 Iterable 。例如,可以在Iterator Garden中找到 Iterable 的装饰器,名为 ForeachIterator 装饰任何可预测的作为 Traversable

I think you need to wrap the Iterable first. As an example, a decorator for Iterable can be found in Iterator Garden named ForeachIterator which is decorating anything foreach-able as a Traversable:

$iterator = new ForeachIterator($iterable);
$this->assertEquals( [1, 2, 3], itarator_to_array($iterator));

请注意细节,它还会考虑 Iterable 中的对象那个测试,对于正确的测试来说不够严格。

Take note to the detail, that it would also consider objects Iterable in that test, which is not strict enough for a correct test.

然而,这应该很容易转换为测试中的私有帮助器方法,只能转换数组和遍历对象 - 不是非遍历对象 - 进入迭代器/数组并应用断言:

However this should be easy to translate into a private helper method in your test to only turn arrays and traversable object - not non-traversable objects - into an iterator / array and apply the assertion:

private function assertIterablesEqual(array $expected, iterable $actual, $message = '')
{
    $array = is_array($actual) ? $actual : iterator_to_array($actual);
    $this->assertEquals($expected, $array, $message);
}

这可以进一步提取到断言类中以扩展Phpunit本身

Take请注意, iterator_to_array 将替换具有重复键的条目,从而生成具有重复键的最后一次迭代值的数组。如果您还需要断言迭代键,则可能需要修改或更改遍历方法。

Take note that iterator_to_array will replace entries with duplicate keys, resulting in an array with the last iteration value of duplicate keys. If you need assertion of iteration keys as well, decorating or change of the traversal method might become necessary.

这篇关于在PHPUnit中测试迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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