Best practices to test protected methods with PHPUnit

前端 未结 8 1008
情深已故
情深已故 2020-11-28 17:14

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 thes

8条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 18:00

    You seem to be aware already, but I'll just restate it anyway; It's a bad sign, if you need to test protected methods. The aim of a unit test, is to test the interface of a class, and protected methods are implementation details. That said, there are cases where it makes sense. If you use inheritance, you can see a superclass as providing an interface for the subclass. So here, you would have to test the protected method (But never a private one). The solution to this, is to create a subclass for testing purpose, and use this to expose the methods. Eg.:

    class Foo {
      protected function stuff() {
        // secret stuff, you want to test
      }
    }
    
    class SubFoo extends Foo {
      public function exposedStuff() {
        return $this->stuff();
      }
    }
    

    Note that you can always replace inheritance with composition. When testing code, it's usually a lot easier to deal with code that uses this pattern, so you may want to consider that option.

提交回复
热议问题