phpunit Assertions Assert the Value of a Public, Protected and Private property


Example

PHPUnit has two assertions to check values of class properties:

assertAttributeSame($expected, $actualAttributeName, $actualClassOrObject, $message = '')
assertAttributeNotSame($expected, $actualAttributeName, $actualClassOrObject, $message = '')

These methods will check the value of a object property regardless of the visibility.

Let's start with a class to be tested. It is a simplified class that has three properties, each with a different visibility:

class Color {

    public $publicColor       = "red";
    protected $protectedColor = "green";
    private $privateColor     = "blue";
    
}

Now, to test the value of each property:

class ColorTest extends PHPUnit_Framework_TestCase
{
    public function test_assertAttributeSame() {

        $hasColor = new Color();

        $this->assertAttributeSame("red","publicColor",$hasColor);
        $this->assertAttributeSame("green","protectedColor",$hasColor);
        $this->assertAttributeSame("blue","privateColor",$hasColor);
        
        $this->assertAttributeNotSame("wrong","privateColor",$hasColor);
    }

}

As you can see, the assertion works for any visibility, making it easy to peer into protected and private methods.

In addition, there is assertAttributeEquals, assertAttributeContains, assertAttributeContainsOnly, assertAttributeEmpty...etc, matching most assertions involving comparison.