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 :

 
<?php
/**
 * 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() {
		parent::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:

$this->getResult()->addValue(
			null,
			$this->getModuleName(),
			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 🙂

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s