简体   繁体   English

phpunit中具有受保护方法的抽象类

[英]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. 我一直在尝试在抽象类上使用phpunit进行测试,该抽象类包含将由其子级共享的受保护方法。 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. 在这种情况下,我既不希望这些方法成为公共API(尽管这不会造成伤害,但它感觉不对劲),也不要在每个孩子中测试同一个父操作是否执行正确。

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() 如果受保护的方法是公共的,则应在类之外检查它们还是仍在authenticate()调用
  • If you see this api (will all methods marked as public) wouldn't you be confused about which methods to invoke? 如果您看到此api(将所有方法标记为public),您会不会对要调用的方法感到困惑?

Thank you all. 谢谢你们。 I think this question is tricky and needs some perspective to look into, so I appretiate your comments 我认为这个问题很棘手,需要一些观点来研究,因此,我感谢您的评论

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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