断言PHPUnit对象具有整数属性

时间:2015-10-01 22:24:26

标签: php phpunit

我正在使用PHPUnit,我必须检查json_decode结果。 我有一个包含整数属性的对象,您可以在调试器视图中看到:

Debugger view of my object

当我这样做时:

$this->assertObjectHasAttribute('1507',$object);

我收到错误:

PHPUnit_Framework_Assert::assertObjectHasAttribute() must be a valid attribute name

我的$objectstdClass

的一个实例

3 个答案:

答案 0 :(得分:6)

数字属性异常,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返回一个对象 OR 一个数组

As described in the docs

  

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

     

...

     

ASSOC

     
      
  • 如果为TRUE,则返回的对象将转换为关联数组。
  •   

因此,适当的测试方法是:

function testSomething() {
    $jsonString = '...';
    $array = json_decode($jsonString, true);
    $this->assertArrayHasKey('1507',$array);
}

答案 1 :(得分:0)

assertObjectHasAttribute检查给定对象是否具有给定名称的属性,而不是其值。所以,在你的情况下:

$this->assertObjectHasAttribute('ID',$object);

如果您想查看,可以使用assertEquals

$this->assertEquals(1509, $object->ID);

答案 2 :(得分:0)

没有看到更好的东西,我会使用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);