断言 PHPUnit 对象具有整数属性
Assert PHPUnit that an object has an integer attribute
我正在使用 PHPUnit,我必须检查 json_decode
结果。
我有一个包含整数属性的对象,如您在调试器视图中所见:
当我这样做时:
$this->assertObjectHasAttribute('1507',$object);
我收到一个错误:
PHPUnit_Framework_Assert::assertObjectHasAttribute() must be a valid attribute name
我的 $object
是 stdClass
的实例
assertObjectHasAttribute
检查给定对象是否具有给定名称的属性,而不是其值。所以,在你的情况下:
$this->assertObjectHasAttribute('ID',$object);
如果你想检查它的值,你可以只使用assertEquals
:
$this->assertEquals(1509, $object->ID);
没有更好的办法,我将使用 get_object_vars
将对象转换为数组并改用 assertArrayHasKey
:
$table = json_decode($this->request( 'POST', [ 'DataTableServer', 'getTable' ], $myData));
$firstElement = get_object_vars($table->aaData[0]);
$this->assertArrayHasKey('1507',$firstElement);
$this->assertArrayNotHasKey('1509',$firstElement);
$this->assertArrayHasKey('1510',$firstElement);
$this->assertArrayHasKey('1511',$firstElement);
一个数值属性异常,PHPUnit won't accept it as a valid attribute name:
private static function isAttributeName(string $string) : bool
{
return preg_match('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $string) === 1;
}
因此最好的做法是不要测试对象是否有属性,而是检查数组是否有键。
json_decode
returns 对象 OR 数组
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
...
assoc
- When TRUE, returned objects will be converted into associative arrays.
因此,合适的测试方法是:
function testSomething() {
$jsonString = '...';
$array = json_decode($jsonString, true);
$this->assertArrayHasKey('1507',$array);
}
我正在使用 PHPUnit,我必须检查 json_decode
结果。
我有一个包含整数属性的对象,如您在调试器视图中所见:
当我这样做时:
$this->assertObjectHasAttribute('1507',$object);
我收到一个错误:
PHPUnit_Framework_Assert::assertObjectHasAttribute() must be a valid attribute name
我的 $object
是 stdClass
assertObjectHasAttribute
检查给定对象是否具有给定名称的属性,而不是其值。所以,在你的情况下:
$this->assertObjectHasAttribute('ID',$object);
如果你想检查它的值,你可以只使用assertEquals
:
$this->assertEquals(1509, $object->ID);
没有更好的办法,我将使用 get_object_vars
将对象转换为数组并改用 assertArrayHasKey
:
$table = json_decode($this->request( 'POST', [ 'DataTableServer', 'getTable' ], $myData));
$firstElement = get_object_vars($table->aaData[0]);
$this->assertArrayHasKey('1507',$firstElement);
$this->assertArrayNotHasKey('1509',$firstElement);
$this->assertArrayHasKey('1510',$firstElement);
$this->assertArrayHasKey('1511',$firstElement);
一个数值属性异常,PHPUnit won't accept it as a valid attribute name:
private static function isAttributeName(string $string) : bool
{
return preg_match('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $string) === 1;
}
因此最好的做法是不要测试对象是否有属性,而是检查数组是否有键。
json_decode
returns 对象 OR 数组
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
...
assoc
- When TRUE, returned objects will be converted into associative arrays.
因此,合适的测试方法是:
function testSomething() {
$jsonString = '...';
$array = json_decode($jsonString, true);
$this->assertArrayHasKey('1507',$array);
}