Best practices to test protected methods with PHPUnit

前端 未结 8 968
情深已故
情深已故 2020-11-28 17:14

I found the discussion on Do you test private method informative.

I have decided, that in some classes, I want to have protected methods, but test them. Some of thes

8条回答
  •  情歌与酒
    2020-11-28 17:44

    I'd like to propose a slight variation to getMethod() defined in uckelman's answer.

    This version changes getMethod() by removing hard-coded values and simplifying usage a little. I recommend adding it to your PHPUnitUtil class as in the example below or to your PHPUnit_Framework_TestCase-extending class (or, I suppose, globally to your PHPUnitUtil file).

    Since MyClass is being instantiated anyways and ReflectionClass can take a string or an object...

    class PHPUnitUtil {
        /**
         * Get a private or protected method for testing/documentation purposes.
         * How to use for MyClass->foo():
         *      $cls = new MyClass();
         *      $foo = PHPUnitUtil::getPrivateMethod($cls, 'foo');
         *      $foo->invoke($cls, $...);
         * @param object $obj The instantiated instance of your class
         * @param string $name The name of your private/protected method
         * @return ReflectionMethod The method you asked for
         */
        public static function getPrivateMethod($obj, $name) {
          $class = new ReflectionClass($obj);
          $method = $class->getMethod($name);
          $method->setAccessible(true);
          return $method;
        }
        // ... some other functions
    }
    

    I also created an alias function getProtectedMethod() to be explicit what is expected, but that one's up to you.

提交回复
热议问题