使用 PHPUnit 测试受保护方法的最佳实践 [英] Best practices to test protected methods with PHPUnit

查看:29
本文介绍了使用 PHPUnit 测试受保护方法的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现关于您是否测试私有方法的讨论内容丰富.

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 不允许通过 reflection 进行此操作.

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 测试受保护方法的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆