简体   繁体   中英

Abstract class with protected methods in phpunit

I've been trying to test with phpunit on my abstract class that holds protected methods that will be shared by it children. I've been reading about private/protected methods shouldn't be tested because that makes the code brittle. In this case, I don't want those methods to be public API (although that wouldn't hurt, Its something that doesn't feels right) nor would I want to test in every child if the same parent action is well executed.

So, as an example explains more, I'll try to post a simple one

abstract class AbstractAuthenticator
{
    abstract function authenticate();

    protected function checkUserPrivilege()
    {
        ... code
    }

    protected function checkEnvPrivileges()
    {
        ... code
    }

}

class BasicAuth extends AbstractAuthenticator
{

    public function authenticate()
    {
        $this->checkUserPrivilege();
        $this->checkEnvPrivileges();
        ... code
    }
}

class AjaxAuth extends AbstractAuthenticator
{

    public function authenticate()
    {
        $this->checkUserPrivilege();
        $this->checkEnvPrivileges();
        ... code
    }
}

My questions (if may I do more than one) are:

  • Does this code make sense to you?
  • Should be protected methods changed to public
  • If the protected methods are public, should they be checked outside the class or still be called in authenticate()
  • If you see this api (will all methods marked as public) wouldn't you be confused about which methods to invoke?

Thank you all. I think this question is tricky and needs some perspective to look into, so I appretiate your comments

创建一个TestAuth类,并在使用它而不是真实的* Auth对象的AbstractAuthenticatorTest中测试受保护的方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM