Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices to test protected methods with PHPUnit

I found the discussion on Do you test private method informative.

I have decided, that in some classes, I want to have protected methods, but test them. Some of these methods are static and short. Because most of the public methods make use of them, I will probably be able to safely remove the tests later. But for starting with a TDD approach and avoid debugging, I really want to test them.

I thought of the following:

  • Method Object as adviced in an answer seems to be overkill for this.
  • Start with public methods and when code coverage is given by higher level tests, turn them protected and remove the tests.
  • Inherit a class with a testable interface making protected methods public

Which is best practice? Is there anything else?

It seems, that JUnit automatically changes protected methods to be public, but I did not have a deeper look at it. PHP does not allow this via reflection.

like image 275
GrGr Avatar asked Oct 30 '08 09:10

GrGr


People also ask

How do you test a protected method?

To test a protected method using junit and mockito, in the test class (the class used to test the method), create a “child class” that extends the protagonist class and merely overrides the protagonist method to make it public so as to give access to the method to the test class, and then write tests against this child ...

How can protected methods be tested using the unit?

The best way to do this, is to change the private method to protected. That means it can only be accessed by that class and any class that inherits the class where the method lives in. [There is another unsafe option, which is to make it internal and make the assembly's internal visible to the unit test assembly.

Should I test private methods site?

The short answer is that you shouldn't test private methods directly, but only their effects on the public methods that call them. Unit tests are clients of the object under test, much like the other classes in the code that are dependent on the object.

How do I run a PHPUnit test?

How to Run Tests in PHPUnit. You can run all the tests in a directory using the PHPUnit binary installed in your vendor folder. You can also run a single test by providing the path to the test file. You use the --verbose flag to get more information on the test status.


1 Answers

If you're using PHP5 (>= 5.3.2) with PHPUnit, you can test your private and protected methods by using reflection to set them to be public prior to running your tests:

protected static function getMethod($name) {   $class = new ReflectionClass('MyClass');   $method = $class->getMethod($name);   $method->setAccessible(true);   return $method; }  public function testFoo() {   $foo = self::getMethod('foo');   $obj = new MyClass();   $foo->invokeArgs($obj, array(...));   ... } 
like image 159
uckelman Avatar answered Oct 05 '22 21:10

uckelman