Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit-test protected methods?

Tags:

phpunit

Is there a way to unit-test protected or private methods of a class? As it is now, I'm making a lot of methods public in order to be able to test them, which breaks the API.

Edit: Actually answered here: Best practices to test protected methods with PHPUnit

like image 348
Olle Härstedt Avatar asked Oct 17 '25 05:10

Olle Härstedt


1 Answers

You can access your private and/or protected method by using the ReflectionMethod class followed by invoke method, but to invoke the method you also need an instance of your class which in certain situations isn't possible. Based on this one nice example that works is this one:

Get a mock of your class:

$mockedInstance = $this->getMockBuilder(YourClass::class)
        ->disableOriginalConstructor()    // you may need the constructor on integration tests only
        ->getMock();

Get your method to be tested:

$reflectedMethod = new \ReflectionMethod(
    YourClass::class,
    'yourMethod'
);

$reflectedMethod->setAccessible(true);

Call your private/protected method:

$reflectedMethod->invokeArgs(    //use invoke method if you don't have parameters on your method
    $mockedInstance, 
    [$param1, ..., $paramN]
);
like image 53
Marcel Kohls Avatar answered Oct 19 '25 08:10

Marcel Kohls



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!