如何对受保护的方法进行单元测试?

Oll*_*edt 3 phpunit

有没有办法对类的受保护或私有方法进行单元测试?现在,我公开了很多方法以便能够测试它们,这破坏了 API。

编辑:实际上在这里回答:使用 PHPUnit 测试受保护方法的最佳实践

Mar*_*hls 8

ReflectionMethod您可以通过使用类后跟方法来访问私有和/或受保护的方法invoke,但要调用该方法,您还需要类的实例,这在某些情况下是不可能的。基于这个,一个很好的例子是这样的:

模拟一下你的班级:

$mockedInstance = $this->getMockBuilder(YourClass::class)
        ->disableOriginalConstructor()    // you may need the constructor on integration tests only
        ->getMock();
Run Code Online (Sandbox Code Playgroud)

获取要测试的方法:

$reflectedMethod = new \ReflectionMethod(
    YourClass::class,
    'yourMethod'
);

$reflectedMethod->setAccessible(true);
Run Code Online (Sandbox Code Playgroud)

调用您的私有/受保护方法:

$reflectedMethod->invokeArgs(    //use invoke method if you don't have parameters on your method
    $mockedInstance, 
    [$param1, ..., $paramN]
);
Run Code Online (Sandbox Code Playgroud)