PHPUnit: Testing if a protected method was called

Posted by Luiz Damim on Stack Overflow See other posts from Stack Overflow or by Luiz Damim
Published on 2009-11-05T13:36:43Z Indexed on 2010/06/11 3:42 UTC
Read the original article Hit count: 306

Filed under:

I´m trying to test if a protected method is called in a public interface.

<?php
abstract class SomeClassAbstract
{ 
    abstract public foo();

    public function doStuff() 
    {    
        $this->_protectedMethod();
    }

    protected function _protectedMethod();
    {
        // implementation is irrelevant
    }
}

<?php
class MyTest extends PHPUnit_Framework_TestCase
{
    public function testCalled()
    {
        $mock = $this->getMockForAbstractClass('SomeClass');
        $mock->expects($this->once())
             ->method('_protectedMethod');

        $mock->doStuff();
    }
}

I know it is called correctly, but PHPUnit says its never called.

The same happens when I test the other way, when a method is never called:

<?php
abstract class AnotherClassAbstract
{ 
    abstract public foo();

    public function doAnotherStuff() 
    {    
        $this->_loadCache();
    }

    protected function _loadCache();
    {
        // implementation is irrelevant
    }
}

<?php
class MyTest extends PHPUnit_Framework_TestCase
{
    public function testCalled()
    {
        $mock = $this->getMockForAbstractClass('AnotherClass');
        $mock->expects($this->once())
             ->method('_loadCache');

        $mock->doAnotherStuff();
    }
}

The method is called but PHPUnit says that it is not.

What I´m doing wrong?

Edit I wasn´t declaring my methods with double colons, it was just for denoting that it was a public method (interface). Updated to full class/methods declarations.

Edit 2 I should have said that I´m testing some method implementations in an abstract class (edited the code to reflect this). Since I can not instantiate the class, how can I test this?

I´m thinking in creating an SomeClassSimple extending SomeClassAbstract and testing this one instead. Is it the right approach?

© Stack Overflow or respective owner

Related posts about phpunit