php 中的单元测试单例模式方法 __clone()
我目前正在对我制作的自定义类进行单元测试,该类基于 singleton
设计模式。根据代码覆盖率报告,我覆盖了 95.45%。我正在使用 PHPUnit 进行单元测试,并且已经完成了 这篇文章 塞巴斯蒂安·伯格曼。
我剩下的唯一问题是通过魔术方法 __clone() 来测试类克隆。我已将该方法设置为私有以避免实例化
private final function __clone()
{}
编写测试以确保单例不可“克隆”的最佳方法是什么。 (相同的测试最终可以用于测试 __constructor()
)
这并不是一个真正的问题,但这只是我的问题还是测试在 Windows 盒子上运行得比 *nix 盒子慢得多?
I'm currently working on unit testing of a custom class I made, which is based on the singleton
design pattern. Based on the code coverage report I have 95.45% of it covered. I am using PHPUnit
to do the unit testing and I have been through this article
by Sebastian Bergmann.
The only problem I am left with is testing against class cloning throught the magic method __clone()
. I have set that method as private to avoid instantiation
private final function __clone()
{}
What would be the best way to write a test to make sure that the singleton isn't "clonable". (The same test could eventually be used to test the __constructor()
)
Not really a question but is it just me or the tests runs awfully slow on a windows box compared to a *nix box?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请记住,代码覆盖率并不是衡量程序正确程度的标准,100% 覆盖率也不意味着您已经执行了每个代码路径。例如,三元运算符
和复合布尔表达式
被计为单个语句,即使您可能由于短路而仅执行其中的一部分。另外,省略单语句
if
、while
等块周围的大括号会将整个事情变成单个语句。以下内容将在代码覆盖率报告中显示为单个语句,因此您无法判断是否执行了这两种情况(
true
和false
)。我觉得这
太简单了,不可能失败。测试该方法是否抛出异常(使用反射,而您的客户不会这样做)就是测试 PHP 解释器——超出了我书中的范围。
[郑重声明,在达到 100% 代码覆盖率时,我也遇到了一点 OC,但牢记上述事实有助于缓解这种情况,以便我可以继续编写更好的代码。]
Keep in mind that code coverage is not a measure of how correct your program is, nor does 100% coverage mean you've executed every code path. For example, the ternary operator
and compound boolean expressions
are counted as single statements even though you may execute only a portion of them due to short-circuiting. Also, omitting the braces around single-statement
if
,while
, etc. blocks turns the whole thing into a single statement.The following will appear as a single statement in the code coverage report so you can't tell if you've executed both cases (
true
andfalse
).I feel that
is too simple to fail. Testing that the method throws an exception (using reflection no less which your clients won't do) is testing the PHP interpreter--out of scope in my book.
[For the record, I too get a little OC when it comes to reaching 100% code coverage, but keeping the above facts in mind helps to alleviate it so I can move on to writing better code.]
调用克隆或构造函数并检查是否抛出异常。
Call clone or constructor and check if excpetion has been thrown.