LoginSignup
20
21

More than 5 years have passed since last update.

PHPUnitでProtectedなプロパティ、関数をテストする

Last updated at Posted at 2013-02-07

テスト対象コード

SampleClass.php
<?php

class SampleClass
{
    protected $foo = TRUE;

    protected function hoge()
    {
        return TRUE;
    }
}
  • hoge()がTRUEを返すことを検証したい
  • $fooがTRUEであることを検証したい

テストコード

SampleClassTest.php
<?php

require_once 'SampleClass.php';

class SampleClassTest extends PHPUnit_Framework_TestCase
{
    public function testAccessProtectedProperty()
    {
        $foo = self::getProperty('foo');
        $obj = new SampleClass();

        $this->assertTrue($foo->getValue($obj));
    }

    public function testAccessProtectedMethod()
    {
        $foo = self::getMethod('hoge');
        $obj = new SampleClass();

        $this->assertTrue($foo->invokeArgs($obj, array()));
    }

    protected static function getProperty($name)
    {
        $class = new ReflectionClass('SampleClass');

        $property = $class->getProperty($name);
        $property->setAccessible(true);

        return $property;
    }

    protected static function getMethod($name)
    {
        $class = new ReflectionClass('SampleClass');

        $method = $class->getMethod($name);
        $method->setAccessible(true);

        return $method;
    }
}

テスト実行結果

$ phpunit SampleClassTest.php 
PHPUnit 3.6.10 by Sebastian Bergmann.

..

Time: 0 seconds, Memory: 2.50Mb

OK (2 tests, 2 assertions)
  • ReflectionClassを活用することで検証結果を得ることができた
20
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
21