Writing PHP unit-tests : How to add a fake user table entry

Flexibility of the Mediawiki PHP unit-tests wrapper extends to the fact that fake database entries can be made and tested upon without causing any harm to the actual one.
As I scribbled in the earlier post, the class-comments play a vital role, and dont forget to give them like this:

 * Class to test table lookups
 * @group Database
class ModifyUserTableTest extends MediaWikiTestCase {
	function testModifyUserTable() {
        // Lets add a fake user named TestUser, and check that his email is confirmed and then get his User Id  
		$user = User::newFromName( 'TestUser' );
		$user->setEmail( 'bob@example.ext' );


		$this->assertTrue( $user->isEmailConfirmed() );

		$uid = $user->getId();

This would create a fake user TestUser in a fake table – mediawiki_unittest. Later this user can be used for any other testing purpose within the class ! Yay!


Writing PHP Unit tests to verify extension API POST

PHP unit tests are crucial before deployment to make sure that the degree of damage your extension can cause is minimal. How to start was always my worry, and here we go.
Considering I have an API called ‘myapi’ that POST’s string $myvar :

 * Tests for API module
 * @group API
 * @group medium
class ExtensionTest extends ApiTestCase {
	 * @var string
	static $myvar = "This is a test var";

         * This needs to be called on every ApiTestCase childs
        function setUp() {
		$this->doLogin( 'sysop' );
	 * Tests API
	 * assuming you have the myapi as per the guidelines below
	function testAPI() {
		$this->setMwGlobals( 'wgMyGlobalArray', array( '1231' ) );
		list( $apiResult ) = $this->doApiRequest( array(
			'action' => 'myapi',
			'email' => self::$myvar
		) );

		$this->assertEquals( 'job', $apiResult['myapi']['submitted'] );

The job = submitted makes sure that the job is completed, and can be implemented by adding this to the API end:

			array ( 'submitted' => 'job' )

PS: you can run the PHP unit test by running this from MediaWiki-core/

tests/phpunit/phpunit.php extensions/<ExtensionName>/tests/ExtensionTest.php

Funny thing about PHP unit tests in MediaWiki is that, even the comment headers too matter 🙂
Happy Hacking 🙂