php 中的单元测试单例模式方法 __clone()

发布于 2024-10-19 17:44:47 字数 501 浏览 2 评论 0原文

我目前正在对我制作的自定义类进行单元测试,该类基于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风筝在阴天搁浅。 2024-10-26 17:44:47

请记住,代码覆盖率并不是衡量程序正确程度的标准,100% 覆盖率也不意味着您已经执行了每个代码路径。例如,三元运算符

a ? b : c

和复合布尔表达式

if (a < 1 || b > 6)

被计为单个语句,即使您可能由于短路而仅执行其中的一部分。另外,省略单语句 ifwhile 等块周围的大括号会将整个事情变成单个语句。

以下内容将在代码覆盖率报告中显示为单个语句,因此您无法判断是否执行了这两种情况(truefalse)。

if (...)
    foo();

我觉得这

private final function __clone() { }

太简单了,不可能失败。测试该方法是否抛出异常(使用反射,而您的客户不会这样做)就是测试 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

a ? b : c

and compound boolean expressions

if (a < 1 || b > 6)

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 and false).

if (...)
    foo();

I feel that

private final function __clone() { }

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.]

倾城月光淡如水﹏ 2024-10-26 17:44:47

调用克隆或构造函数并检查是否抛出异常。

Call clone or constructor and check if excpetion has been thrown.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文