PHPUnit 并使用反射抛出异常

PHPUnit and throwing exceptions using Reflection

我不一定要寻找具体涉及 Reflection 的答案,任何有效的答案都可以。

我有以下摘要 class 由另一个 class 扩展:

abstract class A_Class{

    protected function returnSomething(array $param = ['some_argument' => false])
    {
        if(!is_bool($param))
        {
            throw new Exception('some message goes here');
        }
    }
}

class B_Class extends A_Class{}

我正在使用 PHPUnit 4.8.27 by Sebastian Bergmann and contributors.

我有以下测试

/**
 * @expectedException \Exception
 */
public function testException()
{
    $method = new ReflectionMethod(B_Class::class, 'returnSomething');
    $method->setAccessible(true);
    $method->invokeArgs(new B_Class(), ['some_argument' => 'string']);
}

当我 运行 我的测试出现以下消息时:

Failed asserting that exception of type "\Exception" is thrown.

我已经 google 转了一圈,但我真的无法找到并回答我做错了什么。老实说,我什至不确定我做错了什么。问题本身可能不是我的代码,而是 Reflection class。我对此了解不多,而且所有的文档都有点,嗯,缺乏。它可能无法抛出反射 class.

中定义的异常

任何正确方向的指示都将不胜感激。


到目前为止我尝试过的:

使用 ReflectionClass 代替 ReflectionMethod:

/**
 * @expectedException \Exception
 */
public function testGetExcerptException()
{
    $method = new ReflectionClass(new B_Class()::class);
    $methodToCall = $method->getMethod('returnSomething');
    $methodToCall->setAccessible(true);
    $methodToCall->invokeArgs(new B_Class(), ['some_argument' => 'string']);
}

将可见性设置为 public,这当然有效,但那样做就违背了目的。


万一有人遇到这个问题。不要做我做的事。甚至 The guy that wrote PHPUnit says it's a bad idea。所有测试的方法应该是 public.

使用 Reflection 的替代解决方案是使用 MockObjects,因为您使用的是 PHPUnit。 PHPUnit 中的模拟允许您为您的 类.

模拟任何 public 和受保护的方法