moodle/lib/simpletest/testunittestusingdb.php
tjhunt f68cb08bbe unit tests: MDL-18607 new way to do unit tests involving the database.
This is not as ambitious as the abortive FakeDBUnitTests scheme, but this one works for simple cases.

There is a new test case class UnitTestCaseUsingDatabase to inherit from. I hope it is sufficiently well documented in its PHPdocs.
* It users $CFG->unittestprefix.
* You can access that database using $this->testdb.
* That database is empty by default, you have to call create_test_table to create the ones you want, and drop_test_table to clean them up in the end. The table definitions are read from the XMLDB file.
* When you are ready to call real Moodle code that users $DB, call switch_to_test_db and then revert_to_real_db when you are done.
* If you forget to call drop_test_table or switch_to_test_db, the class will attempt to clean up after you, but will also print rude developer debug messages telling you not to be stupid.
* There is also a load_test_data method for populating a table from an array.

The is an example of its use in lib/simpletest/testunittestusingdb.php.
2009-03-23 04:12:37 +00:00

34 lines
1.2 KiB
PHP

<?php
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
}
class UnitTestCaseUsingDatabase_test extends UnitTestCaseUsingDatabase {
function test_stuff() {
global $CFG, $DB;
$dbman = $this->testdb->get_manager();
$this->assertFalse($dbman->table_exists('quiz_attempts'));
$this->assertFalse($dbman->table_exists('quiz'));
$this->create_test_table('quiz_attempts', 'mod/quiz');
$this->assertTrue($dbman->table_exists('quiz_attempts'));
$this->assertFalse($dbman->table_exists('quiz'));
$this->load_test_data('quiz_attempts',
array('quiz', 'uniqueid', 'attempt', 'preview', 'layout'), array(
array( 1 , 1 , 1 , 0 , '1,2,3,0'),
array( 1 , 2 , 2 , 1 , '2,3,1,0')));
$this->switch_to_test_db();
require_once($CFG->dirroot . '/mod/quiz/locallib.php');
$this->assertTrue(quiz_has_attempts(1));
$this->revert_to_real_db();
$this->drop_test_table('quiz_attempts');
$this->assertFalse($dbman->table_exists('quiz_attempts'));
}
}
?>