SimpleTest conversion

From MoodleDocs

Moodle 2.3


Moodle 2.3 switched to PHPUnit as the recommended unit testing framework. SimpleTest support will be completely removed from Moodle 2.4.

The migration is pretty straightforward:

  1. create new test file in `xxx/tests/yyy_test.php`
  2. copy contents of the old test file
  3. replace
    extends UnitTestCase
    extends basic_testcase
    extends UnitTestCaseUsingDatabase
    extends advanced_testcase
  4. move constructor code to setUp()
  5. fix setUp() and tearDown() to be protected
  6. fix assert syntax
  7. add
    in advanced test cases that modify database
  8. add missing
    global $CFG;
    for includes outside of testcase classes
  9. Usages of
    must be replaced with

Usually the tests using database can be significantly simplified, the performance in PHPUnit is also a lot better.

The old SimpleTest execution page is hidden in 2.3, if you want to execute the old tests go to page on your server.

Assert differences

SimpleTest PHPUnit Notes
$this->assertEqual($expected, $actual)
$this->assertEquals($expected, $actual)
$this->assertNotEqual($expected, $actual)
$this->assertNotEquals($expected, $actual)
$this->assertWithinMargin($expected, $actual, $margin)
$this->assertEquals($expected, $actual, '', $margin)
$this->assertIdentical($expected, $actual)
$this->assertSame($expected, $actual)
$this->assertNotIdentical($expected, $actual)
$this->assertNotSame($expected, $actual)

SimpleTest converts parameter to bool

SimpleTest converts parameter to bool
$this->assertIsA($actual, 'classname')
$this->assertInstanceOf('classname', $actual)
objects instances only
$this->assertIsA($actual, 'array')
$this->assertEquals('array', gettype($actual))
arrays only
$this->assertPattern($pattern, $string)
$this->assertRegExp($pattern, $string)
$this->assertNoPattern($pattern, $string)
$this->assertNotRegExp($pattern, $string)
alternatively use phpdocs: @expectedException exception_classname
alternatively use phpdocs: @expectedException PHPUnit_Framework_Error
various HTML expectations

SimpleTest emulation

Some original SimpleTests can be executed directly via PHPUnit with minimal modifications (try adding global $CFG for includes outside of test case class).