Testing private and protected methods

suggest change

Sometimes it’s useful to test private and protected methods as well as public ones.

class Car
{
    /**
     * @param mixed $argument
     *
     * @return mixed
     */
    protected function drive($argument)
    {
        return $argument;
    }

    /**
     * @return bool
     */
    private static function stop()
    {
        return true;
    }
}

The easiest way to test the drive method is to use reflection. Both test classes extend PHPUnit\Framework\TestCase so assertEquals() is available.

class DriveTest extends PHPUnit\Framework\TestCase
{
    /**
     * @test
     */
    public function testDrive()
    {
        // prepare
        $argument = 1;
        $expected = $argument;
        $car = new \Car();

        $reflection = new ReflectionClass(\Car::class);
        $method = $reflection->getMethod('drive');
        $method->setAccessible(true);

        // invoke logic
        $result = $method->invokeArgs($car, [$argument]);

        // test
        $this->assertEquals($expected, $result);
    }
}

If the method is static you pass null in the place of the class instance

class StopTest extends PHPUnit\Framework\TestCase
{
    /**
     * @test
     */
    public function testStop()
    {
        // prepare
        $expected = true;

        $reflection = new ReflectionClass(\Car::class);
        $method = $reflection->getMethod('stop');
        $method->setAccessible(true);

        // invoke logic
        $result = $method->invoke(null);

        // test
        $this->assertEquals($expected, $result);
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents