jjoselon
jjoselon

Reputation: 2811

How test methods that are not of my test class with PHPUnit, mock, stub

I have this class

<?php 

class Password 
{
    protected function checkPassword()
    {
        $this->callExit();
    }

    protected function callExit()
    {
    exit;
    }    
}

and this is my test:

 public function testAuthorizeExitsWhenPasswordNotSet()
    {


        $badCode = $this->getMockBuilder(Password::class)
            ->setMethods(array('callExit'))
            ->getMock();

        $badCode->expects($this->once())
            ->method('callExit');

        $badCode->checkPassword();

    }

In the earlier class the callExit method is of Password class. My question is, Can I test methods that aren't of the Password class ?

For example in checkPassword method:

protected function checkPassword()
{
    $user = new User;

    $this->callExit();

    $user->fillOut();

}

I want to do a mock for fillOut method, How do I it?

Help me plis !!

Upvotes: 0

Views: 65

Answers (1)

Schleis
Schleis

Reputation: 43760

The way that your code is written, you cannot mock the fillOut method because you are instantiating the User object within the method that you want to test. There is no way to replace the object with a mock like this.

In order to test this method, you should pass in a User object to the checkPassword method. Then you would be able to create a MockUser with the fillOut method mocked.

So your method would look like this:

protected function checkPassword(User $user) {
    $this->callExit();
    $user->fillOut();
}

ALSO

In your code that you have posted, you are calling exit(). Please keep in mind that if this is executed it will halt PHPUnit also.

You are also trying to explicitly test a protected method, you really shouldn't do this. You should only test the public methods of your classes. The protected and private methods should be executed when you are testing the public methods. This lets you refactor the internals of your class and know that you haven't changed the functionality of your class.

If you feel that you need to explicitly test a protected function, this is a sign that you should move that method into a separate class that gets provided to the object that you are testing.

Upvotes: 1

Related Questions