Andrew Andrew - 1 year ago 201
PHP Question

PHPUnit and throwing exceptions using Reflection

I'm not necessarily look for answer involving specifically

, any answer that works will do.

I have the following abstract class which is extended by another class:

abstract class A_Class{

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

class B_Class extends A_Class{}

And I'm using
PHPUnit 4.8.27 by Sebastian Bergmann and contributors.

I have the following test

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

When I run my tests the following message appears:

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

I've google'd around a bit, I can't really find and answer as to what I'm doing wrong. To be perfectly honest I'm not even sure that I'm doing anything wrong. The problem itself may not be with my code as much as it is with the
class. I don't know much about it and all the documentation is kind of, uhm, lacking. It may not be able to throw the exception defined in the reflected class.

Any pointers in the right direction here would be greatly appreciated.

What I've tried so far:

instead of

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

Setting the visibility to public, which of course works, but that kind of defeats the purpose.

In case anybody comes across this question. Don't do what I did. Even the The guy that wrote PHPUnit says it's a bad idea. All tested methods should be public.

Answer Source

An alternative solution from using Reflection, since you are using PHPUnit, is to use MockObjects. Mocks in PHPUnit allow you to mock any public and protected methods for your classes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download