gpt4 book ai didi

PHPUnit assertEquals 严格类型检查

转载 作者:行者123 更新时间:2023-12-02 03:58:24 25 4
gpt4 key购买 nike

我的目标是确保对象图具有预期的值和类型。我想确保每个值都是预期的类型。

为此,assertEquals() 不幸的是没有用:

$this->assertEquals(
[ 'prop' => '0' ],
[ 'prop' => 0 ]
);
// -> no failures

在这种情况下,assertSame() 效果很好:

$this->assertSame(
[ 'prop' => '0' ],
[ 'prop' => 0 ]
);
// Failed asserting that Array &0 (
// 'prop' => 0
// ) is identical to Array &0 (
// 'prop' => '0'
// ).

assertSame() 的问题是它还会检查对象的引用:

$this->assertSame(
(object) [ 'prop' => 0 ],
(object) [ 'prop' => 0 ]
);
// Failed asserting that two variables reference the same object.

我有什么选择?

<小时/>

另外,我不确定为什么这样设计 - 对我来说,感觉 assertSame() 一次做了两件事(我最多有经过验证的对象类,而不是引用)。

最佳答案

到目前为止,我提出了以下选项:

/**
* @param mixed $expected
* @param mixed $actual
* @param string $message
*/
public function assertObjectGraph($expected, $actual, $message = '')
{
$expected = $this->convertObjectsToHashes($expected);
$actual = $this->convertObjectsToHashes($actual);

$this->assertSame($expected, $actual, $message);
}

/**
* @param mixed $value
* @return mixed
*/
private function convertObjectsToHashes($value)
{
if (is_object($value)) {
$value = ['__CLASS__' => get_class($value)] + get_object_vars($value);
}

if (is_array($value)) {
$value = array_map([$this, __FUNCTION__], $value);
}

return $value;
}

示例:

$this->assertObjectGraph(
(object) [ 'prop' => 0 ],
(object) [ 'prop' => 0 ]
);
// -> ok

$this->assertObjectGraph(
(object) [ 'prop' => 0 ],
(object) [ 'prop' => '0' ],
);
// Failed asserting that Array &0 (
// '__CLASS__' => 'stdClass'
// 'prop' => '0'
// ) is identical to Array &0 (
// '__CLASS__' => 'stdClass'
// 'prop' => 0
// ).

class Test{public $prop = 0;}
$this->assertObjectGraph(
(object) [ 'prop' => 0 ],
new Test()
);
// Failed asserting that Array &0 (
// '__CLASS__' => 'Test'
// 'prop' => 0
// ) is identical to Array &0 (
// '__CLASS__' => 'stdClass'
// 'prop' => 0
// ).

关于PHPUnit assertEquals 严格类型检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38893177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com