1

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

Alwin Kesler
  • 1,450
  • 1
  • 20
  • 41

1 Answers1

0

Create a TestAuth class and test the protected methods in an AbstractAuthenticatorTest that uses it instead of the real *Auth objects.

gontrollez
  • 6,372
  • 2
  • 28
  • 36
  • That's a way to test the methods. The real question is: is this right way to test a class behavior other than its public api? after making three access methods, I've started to understand that the really important factor here is to make sure that the abstract authenticate method calls the implicit actions taken in `checkUserPrivilege()` and `checkEnvPrivileges()` and this can only be checked as assertions in the class' tests – Alwin Kesler Feb 12 '14 at 16:21
  • You must test both that the checkUserPrivilege and checkEnvPrivileges work as expected, and they are called when expected. The former is tested in the AbstractAuthenticatorTest, and the latter, in every *Auth class test. Maybe I'm missing something though. regards – gontrollez Feb 13 '14 at 11:03
  • Thanks @gontrollez. I've got to the same assumptions. I'll check this as the best answer – Alwin Kesler Feb 14 '14 at 21:10