S
S
Sergey Pozdnyakov2019-05-24 12:51:24
PHPUnit
Sergey Pozdnyakov, 2019-05-24 12:51:24

PHPUnit how to test protected methods?

Good day!
I can not understand 1 point in testing - protected and private methods.
About their testing they write something like this


Generally speaking, testing private and protected methods is a bad idea. They are not part of the public interface and are usually implemented through the public methods of the class. So when we test public methods, they implicitly test private and protected methods.

That is, either you have a bad implementation of the class, or test together with the public one.
But, if I have a public method, it uses a couple of private methods that form, for example, various data arrays. And it makes no sense to shine them outside. To test both methods, I need to generate a huge test just for the successful variant. And so I could test these methods separately and be sure of them. And in a public method, it's easy to mock. This greatly reduces the complexity of writing and understanding the test.
In the standard implementation, I did not find an option for such testing. Is on stackoverflow
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(...));
  ...
}

In my opinion, this is a crutch
. Can you explain why this is not implemented in the standard functionality. Or how can I write classes and tests for such options?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question