Last active
November 4, 2015 16:11
-
-
Save gausam/045ac1a2fe09d224ec68 to your computer and use it in GitHub Desktop.
How to mock Expression Engine global object in PHPUnit Tests when developing EE plugins
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//So this would be our plugin file | |
Class Chiko { | |
public $ee; | |
public function __construct() | |
{ | |
$this->ee =& get_instance(); | |
} | |
public function yes() | |
{ | |
return $this->ee->addLee('Sam'); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//The file with the tests, which extends our base tests class | |
class LeeTest extends \TestCase { | |
public function test_le() | |
{ | |
$this->EE = \Mockery::mock('EEMock');//Create mock object, attach to our global EE | |
$this->EE->shouldReceive('addLee') //Proceed as normal from here | |
->with('Sam') | |
->andReturn('SamLee'); | |
$chiko = new Chiko();//Won't knwow what hit it | |
$this->assertEquals('SamLee', $chiko->yes('Sam'));//Profit | |
} | |
public function test_le2() | |
{ | |
$this->EE = \Mockery::mock('EXE'); | |
$this->EE->shouldReceive('addLee') | |
->with('Sam') | |
->andReturn('SamHoio'); | |
$chiko = new Chiko(); | |
$this->assertEquals('SamHoio', $chiko->yes('Sam'));//Cleans up after itself nicely, otherwise this would fail | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Base test class | |
global $eeObject;//Global variable we'll be playing around with; | |
function get_instance()//global function to return instance of global object | |
{ | |
global $eeObject; | |
return $eeObject; | |
} | |
class TestCase extends \PHPUnit_Framework_TestCase | |
{ | |
public $EE;//But we'll access global object abobe as a property of our test class, for cleanliness' sake | |
public function setUp() | |
{ | |
Mockery::getConfiguration()->allowMockingMethodsUnnecessarily(false);//and any other things you need to do. | |
global $eeObject;//Pull this in | |
$eeObject = null;//Clean it per run (although I think it'll be cleaned up auto) | |
$this->EE = &$eeObject;// Hook it in by ref into our test class | |
} | |
public function tearDown() | |
{ | |
global $eeObject;//clean up | |
$eeObject = null; | |
$this->EE = null; | |
Mockery::close(); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment