phpunit 抽象类常量
我正在尝试找到一种方法来测试必须存在且匹配/不匹配值的抽象类常量。示例:
// to be extended by ExternalSDKClild
abstract class ExternalSDK {
const VERSION = '3.1.1.';
}
class foo extends AController {
public function init() {
if ( ExternalSDK::VERSION !== '3.1.1' ) {
throw new Exception('Wrong ExternalSDK version!');
}
$this->setExternalSDKChild(new ExternalSDKChild());
}
}
限制...我们使用的框架不允许在 init() 方法中进行依赖项注入。 (建议重构 init() 方法可能是可行的方法...)
我运行的单元测试和代码覆盖率涵盖了除异常之外的所有内容。我想不出一种方法可以使ExternalSDK::Version 与它的实际情况不同。
欢迎所有想法
I'm trying to find a way to test a abstract class constant that must exist and match/not match a value. Example:
// to be extended by ExternalSDKClild
abstract class ExternalSDK {
const VERSION = '3.1.1.';
}
class foo extends AController {
public function init() {
if ( ExternalSDK::VERSION !== '3.1.1' ) {
throw new Exception('Wrong ExternalSDK version!');
}
$this->setExternalSDKChild(new ExternalSDKChild());
}
}
Limitations... The framework we use doesn't allow dependency injection in the init() method. (Suggestion to refactor the init() method could be the way to go...)
The unit tests and code coverage I have run, cover all but the Exception. I can't figure out a way to make the ExternalSDK::Version to be different from what it is.
All thoughts welcome
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,将对 new 的调用重构为单独的方法。
其次,添加一个获取版本的方法,而不是直接访问常量。 PHP 中的类常量在解析时被编译到文件中,并且无法更改。* 由于它们是静态访问的,因此如果不交换具有相同名称的不同类声明,就无法覆盖它。使用标准 PHP 执行此操作的唯一方法是在单独的进程中运行测试,这是非常昂贵的。
现在进行单元测试。
*Runkit 提供
runkit_constant_redefine()
可能在这里工作。您需要手动捕获异常,而不是使用@expectedException
,以便可以将常量重置回正确的值。或者您可以在tearDown()
中执行此操作。First, refactor the call to
new
into a separate method.Second, add a method to acquire the version instead of accessing the constant directly. Class constants in PHP are compiled into the file when parsed and cannot be changed.* Since they are accessed statically, there's no way to override it without swapping in a different class declaration with the same name. The only way to do that using standard PHP is to run the test in a separate process which is very expensive.
And now for the unit test.
*Runkit provides
runkit_constant_redefine()
which may work here. You'll need to catch the exception manually instead of using@expectedException
so you can reset the constant back to the correct value. Or you can do it intearDown()
.