Assert PHPUnit that the object has an integer attribute

I am using PHPUnit and I need to check the json_decode result. I have an object containing an integer attribute, as you can see in the debugger view:

Debugger viewing my object

When I do this:

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

I get an error message:

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

My $object is an instance of stdClass

+5
source share
3 answers

A numeric property is not normal and PHPUnit will not 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; } 

Therefore, it is best not to test whether the object has an attribute, but rather checks to see if the array has a key.

json_decode returns an object OR an array

As described in the docs :

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

...

associative

  • When TRUE, the returned objects will be converted to associative arrays.

Appropriate Test Method:

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

assertObjectHasAttribute verifies that the given object has an attribute of the given name, and not its value. So in your case:

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

If you want to check its value , you can simply use assertEquals :

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

Seeing nothing better, I'm going to convert the object to an array using get_object_vars and use 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); 
0
source

Source: https://habr.com/ru/post/1232756/


All Articles