我有以下函数。
function get_svg_dimensions($svg)
{
$svg = simplexml_load_file($svg);
$width = 0;
$height = 0;
if ($svg) {
$attributes = $svg->attributes();
if (isset($attributes->width, $attributes->height)) {
$width = intval($attributes->width);
$height = intval($attributes->height);
} elseif (isset($attributes->viewBox)) {
$sizes = explode(' ', $attributes->viewBox);
if (isset($sizes[2], $sizes[3])) {
$width = intval($sizes[2]);
$height = intval($sizes[3]);
}
}
}
return ['width' => $width, 'height' => $height];
}
我想模拟 $attributes = $svg->attributes();
.
这就是测试。
public function testGetSvgDimension()
{
$mockAttributes = [
'width' => '100px',
'height' => '100px',
'viewBox' => '0 0 100 100',
];
$mockSimpleXmlElement = (object)[
'@attributes' => $mockAttributes
];
$expected_value = [
'width' => '100px',
'height' => '100px',
];
Functions\when('simplexml_load_file')->justReturn($mockSimpleXmlElement);
$request = $this->createMock(SimpleXMLElement::class);
$request->expects($this->once())->method('attributes')->willReturn($mockAttributes);
static::assertEquals($expected_value, sg_core_t_get_svg_dimensions('mock_path'));
}
这一行出现了以下错误 $request = $this->createMock(SimpleXMLElement::class);
:
Mock_SimpleXMLElement_eba23fd5::__phpunit_setReturnValueGeneration(): Node no longer exists
我已经尝试使用 Traversable::class
而不是 SimpleXMLElement::class
在 $request = $this->createMock(Traversable::class);
但在这种情况下,我得到以下警告。
Trying to configure method "attributes" which cannot be configured because it does not exist, has not been specified, is final, or is static
这是把这个函数的测试覆盖率变成了0.
PHPUnit
版本是 7.5.20
. 我不能升级到8或9,因为网站是用WordPress建立的,WordPress目前只兼容于 PHPUnit
以至于 7.x
. PHP
版本是 7.2.26
.
谁能帮帮我?
找到了一个解决方案。
基本上,我做错了什么,是我在这里返回了一个错误的值。Functions\when('simplexml_load_file')->justReturn($mockSimpleXmlElement);
然后试图模拟 SimpleXMLElement
类。
我应该做的是,我应该已经返回一个。SimpleXMLElement
嘲讽 simplexml_load_file
并为其添加属性。
查看完整的代码。
public function dataProvider_GetSvgDimensions()
{
return [
'height and width attributes exist on the svg' => [
(object)[
'width' => '100',
'height' => '100',
]
],
'height and width attributes do not exist on the svg - viewBox exists' => [
(object)[
'viewBox' => '0 0 100 100',
]
],
];
}
/**
* @dataProvider dataProvider_GetSvgDimensions
*
* @param $mockAttributes
*/
public function testGetSvgDimension($mockAttributes)
{
$expected_value = [
'width' => '100',
'height' => '100',
];
$mockSimpleXmlElement = new SimpleXMLElement('<root />');
foreach ($mockAttributes as $attr => $value) {
$mockSimpleXmlElement->addAttribute($attr, $value);
}
Functions\when('simplexml_load_file')->justReturn($mockSimpleXmlElement);
static::assertEquals($expected_value, sg_core_t_get_svg_dimensions('mock_path'));
}