问题描述:

Using DrupalUnitTestCase to unit test a Drupal module, fails. I probably forget something.

The test runs fine untill I create an instance of some class:

$foo = new FooBar();

In that case, Drupal decides to do some magic and attempts to call the database, in order to find some file in its registry.

 Test PDOStatement->execute() failed: <em class="placeholder">PDOException</em>: SQLSTATE[42S02]: Base table [error]

or view not found: 1146 Table &#039;td_development.simpletest50921registry&#039; doesn&#039;t exist: SELECT

filename FROM {registry} WHERE name = :name AND type = :type; Array

(

[:name] =&gt; FooBar

[:type] =&gt; interface

)

DrupalUnitTestCase, as opposed to DrupalWebTestCase do not set up a database, by design. So the reason why this fails is clear.

However, I don't want Drupal to go looking in a database when all I want is to create some instance. How to avoid Drupal looking up the file in its registry?

网友答案:

You probably can't.

The possibilities of using UnitTestCase as the parent class are very limited. As soon as you do anything that requires the database (and creating a new class does because the autoload features of Drupal 7 depend on the database), you have to use WebTestCase.

The only thing that might work is explicitly including all files that are required for that class to work. Because the autoload is only called if the class does not exist yet (could also be a class that your class uses or depends on). But that is relatively fragile and you will always have to include all these files manually in the correct order, which means that your unit tests depend on the inner workings of your class. Which isn't nice either.

网友答案:

You can also try this

spl_autoload_register('your_function');
if (function_exists('drupal_autoload_class')) {
  spl_autoload_unregister('drupal_autoload_class');
  spl_autoload_register('drupal_autoload_class');
  spl_autoload_unregister('drupal_autoload_interface');
  spl_autoload_register('drupal_autoload_interface');
}

This will move the Drupal autoload to the bottom and solve the problem.

相关阅读:
Top