Moodle Unit Testing with PHP Unit

I need to do some unit testing on Moodle 2.8 with a version that was pretty difficult to work on because of all the hacking of the core that had been done.

cd /mymoodle_install/public_html

#Run composer and install packages into /mymoodle_install/public_html/vendor
composer update

#Update the /mymoodle_install/public_html/config.php with test settings
$CFG->phpunit_prefix = ‘phpu_’;
$CFG->phpunit_dataroot = ‘/mymoodle_install/my_unit_tests’;

$CFG->phpunit_dbtype = ‘mysqli’; // ‘pgsql’, ‘mariadb’, ‘mysqli’, ‘mssql’, ‘sqlsrv’ or ‘oci’
$CFG->phpunit_dblibrary = ‘native’; // ‘native’ only at the moment
$CFG->phpunit_dbhost = ‘127.0.0.1’; // eg ‘localhost’ or ‘db.isp.com’ or IP
$CFG->phpunit_dbname = ‘test_db_name’; // database name, eg moodle
$CFG->phpunit_dbuser = ‘test’; // your database username
$CFG->phpunit_dbpass = ‘testpass’; // your database password

# Initialise the database
php admin/tool/phpunit/cli/init.php

#This failed as I was running MySQL 5.7.10 so I needed to change lib/dml/mysqli_native_moodle_database.php line 184
$sql = “SELECT @@storage_engine”;
#To
$sql = “SELECT @@default_storage_engine”;
# And change
$engine = $rec[‘@@storage_engine’];
# To
$engine = $rec[‘@@default_storage_engine’];

#Go to PHPStorm, bring up preferences (Mac), settings (Win)
Languages & Frameworks > PHP > PHPUnit

Use custom autoloader
/mymoodle_install/public_html/vendor/autoload.php

Test Runner
Tick ‘Default configuration file’
/mymoodle_install/public_html/phpunit.xml

Everything worked fine although the installation of Moodle that I was using was pretty broken and needed multiple updates to get the test database installing without errors.

One of the errors I needed to fix was code like this

SELECT c.id, c.fullname, c.summary from mdl_course c
                        INNER JOIN
                        mdl_block_course_bookmarks b ON c.id = b.seid

This caused a problem because using the full name of the table in SQL meant the unit test database was not able to find the right table (which would have been something like phpu_course). The correct way to do this was

SELECT c.id, c.fullname, c.summary from {course} c
                        INNER JOIN
                        {block_course_bookmarks} b ON c.id = b.seid

Comments are closed.