Best practices to test protected methods with PHPUnit

前端 未结 8 995
情深已故
情深已故 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:37

    teastburn has the right approach. Even simpler is to call the method directly and return the answer:

    class PHPUnitUtil
    {
      public static function callMethod($obj, $name, array $args) {
            $class = new \ReflectionClass($obj);
            $method = $class->getMethod($name);
            $method->setAccessible(true);
            return $method->invokeArgs($obj, $args);
        }
    }
    

    You can call this simply in your tests by:

    $returnVal = PHPUnitUtil::callMethod(
                    $this->object,
                    '_nameOfProtectedMethod', 
                    array($arg1, $arg2)
                 );
    

提交回复
热议问题