Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHPUnit中测试可测试性_Php_Arrays_Iterator_Phpunit_Php 7.1 - Fatal编程技术网

在PHPUnit中测试可测试性

在PHPUnit中测试可测试性,php,arrays,iterator,phpunit,php-7.1,Php,Arrays,Iterator,Phpunit,Php 7.1,在PHPUnit中,很容易断言两个数组包含相同的值: $this->assertEquals( [1, 2, 3], [1, 2, 3] ); PHP的最新版本使迭代器和生成器的使用更具吸引力,PHP7.1也被引入。这意味着我可以编写函数来获取并返回iterable,而不必绑定到我使用的是一个普通的数组或一个懒惰的生成器 如何断言返回iterable的函数的返回值?理想情况下,我可以做类似的事情 $this->assertIterablesEqual( ['expected',

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

 $this->assertEquals( [1, 2, 3], [1, 2, 3] );
PHP的最新版本使迭代器和生成器的使用更具吸引力,PHP7.1也被引入。这意味着我可以编写函数来获取并返回
iterable
,而不必绑定到我使用的是一个普通的
数组
或一个懒惰的
生成器

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

 $this->assertIterablesEqual( ['expected', 'values'], $iterable );
有这样的功能吗?或者,是否有一种合理的测试方法,不需要在我的测试中添加一堆点命令式代码?

您可以使用函数,例如:

 $expected = [1, 2, 3];
 $this->assertEquals( $expected, iterator_to_array($iterable) );
这也适用于


希望这对您有所帮助

我想您需要先包装一下Iterable。例如,可以在名为Iterator Garden的迭代器中找到Iterable的装饰器,它是一个可遍历的:

注意细节,也可以考虑在该测试中迭代的对象,这对于一个正确的测试来说不够严格。

但是,在您的测试中,这应该很容易转化为私有助手方法,以便仅将数组和可遍历对象(而不是不可遍历对象)转换为迭代器/数组,并应用断言:

private function assertIterablesEqual(array $expected, iterable $actual, $message = '')
{
    $array = is_array($actual) ? $actual : iterator_to_array($actual);
    $this->assertEquals($expected, $array, $message);
}
这可以更进一步


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

如果您有一个
可遍历的
,并且只关心值yes,那么这就行了。但是,它不适用于
iterable
,因为
iterator\u to\u数组
只接受
可遍历
private function assertIterablesEqual(array $expected, iterable $actual, $message = '')
{
    $array = is_array($actual) ? $actual : iterator_to_array($actual);
    $this->assertEquals($expected, $array, $message);
}