1

Here is the code I'm trying to unit test:

public function getDao () {
    $dao = '';

    if (isset($this->_dao)) {
        $dao = $this->_dao;
    } else {
        $dao = new $this->_daoClassName; 
    }

    return $dao;
}

The class is an abstract class, and $_daoClassName is a protected variable. Each concrete class sets a value for $_daoClassName

How can I unit test this code? I'm trying to use PHPUnit's $this->getMockForAbstractClass() but I don't think I can override the protected method. Alternatively, is there a better pattern I should be using on this getDao() method?

1
  • Create a dummy class that extends yours and defines _daoClassName with an expected value. Commented Jul 6, 2013 at 13:41

1 Answer 1

1

I would highly recommend a function like:

abstract protected function getDaoClassName();

Which should be implement by sub classes. (enforced through abstract)

Then you can configure your mock in a way that the function returns a certain value:

$stub = $this->getMockForAbstractClass('YourClass');
$stub->expects($this->any())
     ->method('getDaoClassName')
     ->will($this->returnValue('SomeDaoClass'));

And then test the method:

$dao = $stub->getDao();
$this->assertEquals('SomeDaoClass', get_class($dao));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.