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