Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert PHPUnit that an object has an integer attribute

Tags:

php

phpunit

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 :

Debugger view of my object

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

like image 354
Nicolas Thery Avatar asked Oct 01 '15 22:10

Nicolas Thery


People also ask

What is assertfinite in PHPUnit?

assertFinite () is the inverse of this assertion and takes the same arguments. $ phpunit InfiniteTest PHPUnit 9.5.0 by Sebastian Bergmann and contributors.

What is assertisnotobject in PHPUnit?

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!

What is the inverse of assertclassnothasattribute in PHP?

assertClassNotHasAttribute () is the inverse of this assertion and takes the same arguments. $ phpunit ClassHasAttributeTest PHPUnit 9.5.0 by Sebastian Bergmann and contributors.

What is assertnotsame in sametest PHPUnit?

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.


2 Answers

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 array

As 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);
}
like image 123
AD7six Avatar answered Nov 02 '22 23:11

AD7six


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);
like image 31
Mureinik Avatar answered Nov 02 '22 23:11

Mureinik