Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/264.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHPUnit和使用反射引发异常_Php_Reflection_Phpunit - Fatal编程技术网

PHPUnit和使用反射引发异常

PHPUnit和使用反射引发异常,php,reflection,phpunit,Php,Reflection,Phpunit,我不一定要寻找具体涉及反射的答案,任何有效的答案都可以。 我有以下抽象类,它由另一个类扩展: abstract class A_Class{ protected function returnSomething(array $param = ['some_argument' => false]) { if(!is_bool($param)) { throw new Exception('some message go

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

我有以下抽象类,它由另一个类扩展:

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{}
我正在使用Sebastian Bergmann和贡献者的
PHPUnit 4.8.27。

我有以下测试

/**
 * @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.

我用谷歌搜索了一下,我真的无法找到并回答我做错了什么。说实话,我甚至不确定自己做错了什么。我的代码本身可能不像
Reflection
类那样存在问题。我对它了解不多,所有的文档都有点,嗯,缺乏。它可能无法抛出反射类中定义的异常

如果您能在这里指出正确的方向,我们将不胜感激


到目前为止,我所尝试的:

使用
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']);
}
设置对公众的可见性,这当然是可行的,但这样做有违目的



万一有人遇到这个问题。别做我做的事。就连这个。所有经过测试的方法都应该是公开的。

由于您使用的是PHPUnit,因此使用反射的另一种解决方案是使用。
phpun中的mock不允许您为类模拟任何公共和受保护的方法。

您使用的是
\Exception
还是
SomeNamespace\Exception
?尽管所有异常都扩展了
\Exception
。。。也许可以试试
$this->expectException()
也许这有帮助:@AlexTartan刚刚用
$this->setExpectedException(\Exception::class)试过了
$this->setExpectedException(new\Exception())(这是个坏主意,有大量错误记录)。同样的问题。从技术上讲,注释
@expectedException\Exception
$this->expectException()
完全相同,但我认为注释在
v4.9.x
或类似版本中被弃用。我认为是一个打字错误。您的代码
$method->invokeArgs(新的B_类(),['some_参数'=>'string'])应该是
$method->invokeArgs(新的B_类(),[['some_参数=>'string']])
因为您必须在invokeArgs方法中传递
数组
数组
。@Whiteulver哪一个?见鬼,如果代码中的某个地方有输入错误,我会非常高兴,尽管这不是实际的代码。@Whiteulver刚刚尝试过,同样的事情:(.
1)HtmlBuilderTest::TestGetExceptExceptException无法断言抛出了“\exception”类型的异常。
希望它能工作……谢谢,伙计,测试终于通过了:d