I'm using PHPUnit and I have to check a json_decode
result.
I have an object containing an integer attribute as you can see in the debugger view :
When I do this :
$this->assertObjectHasAttribute('1507',$object);
I get an error :
PHPUnit_Framework_Assert::assertObjectHasAttribute() must be a valid attribute name
My $object
is an instance of stdClass
assertFinite () is the inverse of this assertion and takes the same arguments. $ phpunit InfiniteTest PHPUnit 9.5.0 by Sebastian Bergmann and contributors.
assertIsNotObject () is the inverse of this assertion and takes the same arguments. $ phpunit ObjectTest PHPUnit | version | .0 by Sebastian Bergmann and contributors. F Time: 0 seconds, Memory: 5 .00Mb There was 1 failure: 1) ObjectTest::testFailure Failed asserting that null is of type "object" . /home/sb/ObjectTest.php:8 FAILURES!
assertClassNotHasAttribute () is the inverse of this assertion and takes the same arguments. $ phpunit ClassHasAttributeTest PHPUnit 9.5.0 by Sebastian Bergmann and contributors.
Tests: 1, Assertions: 2, Failures: 1. Reports an error identified by $message if the two variables $expected and $actual do not have the same type and value. assertNotSame () is the inverse of this assertion and takes the same arguments. $ phpunit SameTest PHPUnit 9.5.0 by Sebastian Bergmann and contributors.
A numeric property is abnormal, and 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;
}
Therefore the best thing to do is not test if the object has an attribute, but rather check if an array has a key.
json_decode
returns an object OR an arrayAs described in the docs:
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.
An appropriate test method is therefore:
function testSomething() {
$jsonString = '...';
$array = json_decode($jsonString, true);
$this->assertArrayHasKey('1507',$array);
}
assertObjectHasAttribute
checks that the given object has an attribute of the given name, not its value. So, in your case:
$this->assertObjectHasAttribute('ID',$object);
If you want to check its value, you could just use assertEquals
:
$this->assertEquals(1509, $object->ID);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With