SimpleTest:如何断言抛出 PHP 错误?
如果我是正确的,SimpleTest 将允许您断言抛出了 PHP 错误。 但是,根据文档,我无法弄清楚如何使用它。 我想断言传递给构造函数的对象是 MyOtherObject 的实例
class Object {
public function __construct(MyOtherObject $object) {
//do something with $object
}
}
//...and in my test I have...
public function testConstruct_ExpectsAnInstanceOfMyOtherObject() {
$notAnObject = 'foobar';
$object = new Object($notAnObject);
$this->expectError($object);
}
我哪里出错了?
If I am correct, SimpleTest will allow you to assert a PHP error is thrown. However, I can't figure out how to use it, based on the documentation. I want to assert that the object I pass into my constructor is an instance of MyOtherObject
class Object {
public function __construct(MyOtherObject $object) {
//do something with $object
}
}
//...and in my test I have...
public function testConstruct_ExpectsAnInstanceOfMyOtherObject() {
$notAnObject = 'foobar';
$object = new Object($notAnObject);
$this->expectError($object);
}
Where am I going wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
类型提示会抛出 E_RECOVERABLE_ERROR,自 PHP 5.2 版起,SimpleTest 可以捕获该错误。 以下内容将捕获包含文本“必须是……的实例”的任何错误。 PatternExpectation 的构造函数采用 perl 正则表达式。
Type hinting throws E_RECOVERABLE_ERROR which can be caught by SimpleTest since PHP version 5.2. The following will catch any error containing the text "must be an instance of". The constructor of PatternExpectation takes a perl regex.
PHP 同时存在错误和异常,它们的工作方式略有不同。 将错误的类型传递给类型提示函数将引发异常。 你必须在你的测试用例中抓住这一点。 例如:
或简单地:
但请注意,这将在发生异常的行之后停止测试。
PHP has both errors and exceptions, which work slightly different. Passing a wrong type to a typehinted function will raise an exception. You have to catch that in your test case. Eg.:
or simply:
But note that this will halt the test after the line where the exception occurs.
事实证明,SimpleTest 实际上并不支持这一点。 您无法在 SimpleTest 中捕获致命的 PHP 错误。 类型提示很棒,但你无法测试它。 类型提示会引发致命的 PHP 错误。
Turns out, SimpleTest doesn't actually support this. You can't catch Fatal PHP errors in SimpleTest. Type hinting is great, except you can't test it. Type hinting throws fatal PHP errors.
你必须在错误发生之前预料到错误,然后 SimpleTest 会吞掉它并算为一次通过,如果测试结束并且没有错误,那么它将失败。 (对于 PHP(非致命)错误和异常,expectError 和 ExpectException 的作用相同。)
you have to expect the error before it happens, then SimpleTest will swallow it and count a pass, if the test gets to the end and there is no error then it will fail. (there's expectError and expectException that act in the same way, for PHP (non-fatal) errors and Exceptions, respectively.)