简体   繁体   English

如何在PHP中以最简单的方式预期致命错误

[英]How to expect fatal errors with simpletest in php

I am attempting to write a test case to ensure a Singleton class cannot be instantiated. 我试图编写一个测试用例,以确保无法实例化Singleton类。 The constructor for the Singleton is defined to be private so my test is as follows: Singleton的构造函数定义为私有,因此我的测试如下:

$this->expectError();
$test = new TestSingletonClassA();

Instead of catching the error and passing the test, I get a 'PHP Fatal error: Call to private Singleton::__construct()'. 而不是捕获错误并通过测试,我得到了“ PHP致命错误:调用私有Singleton :: __ construct()”。 I've also tried passing a PatternExpectation as a parameter to expectError, but that didn't work either. 我也尝试过将PatternExpectation作为参数传递给ExpectError,但这也不起作用。 Do you have any suggestions? 你有什么建议吗?

Some background: php5.3, simpletest1.1a 一些背景:php5.3,simpletest1.1a

If your php code throws a FATAL ERROR, it will never get to the phpunit, so you have to write "right" code in order to test it. 如果您的php代码抛出致命错误,它将永远无法到达phpunit,因此您必须编写“正确的”代码才能对其进行测试。 If you call a private method, it will throw an excepcion, so it won't get to the phpunit. 如果调用私有方法,它将抛出异常,因此不会进入phpunit。 You have to change that. 您必须更改它。

I think you have to mock the object. 我认为您必须嘲笑该对象。 Try these posts about this subject (it's a series of 4 posts) and these slides (from slide #43) . 试试这些关于该主题的帖子 (共4个帖子)和这些幻灯片 (来自幻灯片#43)。

Unit testing frameworks cannot catch such things. 单元测试框架无法捕捉到这些东西。 But you can with PHPT and similar regression test frameworks. 但是您可以使用PHPT和类似的回归测试框架。

You might have to jump through some hoops to hook it into PHPUnit, but there's probably ways to integrate it with the remaining tests. 您可能需要跳过一些步骤才能将其连接到PHPUnit,但是可能存在将其与其余测试集成的方法。 You'll just have to separate assertions and the special case where you expect the fatal error. 您只需要将断言和特殊情况分开,就可以预见致命错误。

i don't think it's possible to do it that way.. fatal errors are not catchable as i've understood it. 我认为不可能那样做。致命错误是无法理解的,因为我已经理解了。 you could use reflection to get the constructor method, and then make sure it has the access modifier "private". 您可以使用反射来获取构造函数方法,然后确保它具有访问修饰符“ private”。

this is hard to test in most languages. 这在大多数语言中都很难测试。 for example java, c# and c++ would not even let you compile this code. 例如java,c#和c ++甚至都不允许您编译此代码。 so it could never be run at all D: 所以它永远不会运行D:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM