问题描述
我在您测试私有方法信息量中找到了讨论.
I found the discussion on Do you test private method informative.
我已经决定,在某些类中,我想拥有受保护的方法,但是要对其进行测试.这些方法中的一些是静态的且简短的.因为大多数公共方法都使用了它们,所以我以后也许可以安全地删除测试.但是,为了从TDD方法入手并避免调试,我真的想对其进行测试.
I have decided, that in some classes, I want to have protected methods, but test them.Some of these methods are static and short. Because most of the public methods make use of them, I will probably be able to safely remove the tests later. But for starting with a TDD approach and avoid debugging, I really want to test them.
我想到了以下内容:
- Method Object as adviced in an answer seems to be overkill for this.
- Start with public methods and when code coverage is given by higher level tests, turn them protected and remove the tests.
- Inherit a class with a testable interface making protected methods public
哪种是最佳做法?还有什么吗?
Which is best practice? Is there anything else?
似乎,JUnit会自动将受保护的方法更改为公共方法,但我对此没有更深入的了解. PHP不允许通过反射.
It seems, that JUnit automatically changes protected methods to be public, but I did not have a deeper look at it. PHP does not allow this via reflection.
推荐答案
如果您将PHP5(> = 5.3.2)与PHPUnit一起使用,则可以通过使用反射将它们设置为公共方法来测试私有和受保护的方法.在运行测试之前:
If you're using PHP5 (>= 5.3.2) with PHPUnit, you can test your private and protected methods by using reflection to set them to be public prior to running your tests:
protected static function getMethod($name) {
$class = new ReflectionClass('MyClass');
$method = $class->getMethod($name);
$method->setAccessible(true);
return $method;
}
public function testFoo() {
$foo = self::getMethod('foo');
$obj = new MyClass();
$foo->invokeArgs($obj, array(...));
...
}
这篇关于使用PHPUnit测试受保护方法的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!