HorusKol
HorusKol

Reputation: 8706

Mocking a class is causing problems in other tests which use the original class

I started with the following test, and all was good:

class Search_Model_Mapper_Search_GetDbTableTest extends PHPUnit_Framework_TestCase
{
  public function testGetDbTable()
  {
    $mapper = new Search_Model_Mapper_Search();
    $dbClass = new ReflectionClass($mapper->getDbTable('Search_Model_DbTable_Search'));
    $this->assertEquals('Search_Model_DbTable_Search', $dbClass->getName());
  }
}

Then, I added another test elsewhere:

class Search_IndexController_FulltextActionTest extends PHPUnit_Framework_TestCase
{
  public function testQueryNoResults() {
    $mapper = $this->getMockBuilder("Search_Model_Mapper_Search")
      ->disableOriginalConstructor()
      ->setMethods(array("find", "count"))
      ->getMock();
}

And now I'm getting a fatal error Call to undefined method Search_Model_Mapper_Search::getDbTable()

I used reflection in the original test to find the file that the Search_Model_Mapper_Search class is defined in, and it is now in phar:///usr/local/bin/phpunit/phpunit-mock-objects/Framework/MockObject/Generator.php(335) : eval()'d code, and when I call getMethods on the reflected class I get an empty array.

If I skip or delete the test which mocks the class, I get a full list of methods when I call getMethods in the original test.

Is there something I missed to ensure each test is run cleanly, or is this a bug in PHPUnit and/or PHPUnit Mock Objects?

I'm using PHPUnit 4.3.1 via phar

Upvotes: 1

Views: 174

Answers (1)

gontrollez
gontrollez

Reputation: 6548

This happens usually because the original class is not loaded (or autoloaded) before being mocked. So the mocking framework assumes it does not exist and creates a dummy class (with no methods).

Try requiring the original class before mocking it.

Upvotes: 2

Related Questions