Is it at all possible to do this in PHP: (Solved: Yes it is possible to do this.)
/// Unit test for class some below
class some_test{
function test_foo1 () {
$var->fileName = "name";
$var->fileLocation = "Location";
$var->fileType = "png";
$var->someFunction() = foo2();
// Do $var->someFunction = foo2();
}
function foo2() {
....do something ....
}
}
// Class Under test
class some {
function foo1(){
$var = getObjWith_someFunction();
if(isset($var))
$var->someFunction();
}
}
I need to do this because when I am writing this unit test for a class where someFunction() is being called, it says that the someFunction() does not exist. So I need to create a dummy function in the test case.
Code example:
class pictureManager {
public function getPicture() {
try {
$picObj = getPicObj(1);
}
catch (Exception) {
if (isset($picObj)) $picObj->showMessage();
}
}
public function getPicObj($id){ // Need to mock this function to return picClass object
return new picClass($id);
}
}
class picClass {
public $id;
public function __construct($id){
$this->id = id;
}
public function showMessage(){
echo "in this function";
}
}
Unit Test for class pictureManager:
class pictureManager_test extends PHPUnit_Framework_TestCase {
public function test_getPicture() {
$fixture = $this->getMock('pictureManager', array('getPicObj'));
$arg = 1;
// Here I am creating the return obj on the fly. Can this be done? (Yes)
$returnValue->id = 1;
>>> $returnValue->showMessage() = someThing(); // This is where I am stuck
//Solution: $returnValue->showMessage = someThing();
//Remove the brackets (). Since I cant answer my question I am writing it here.
$fixture::staticExpects($this->once())
->method('getPicObj')
->with($arg)
->will($this->returnValue($returnValue));
$fixture->getPicture();
}
}
PHP 5.3 is the first version to accept this, so yes it is possible.
But if you are on any previous version, you will need to use the
create_function()function.5.3 also allows dynamic creation of functions in a way similar to lambda functions.
Here’s a sum-up: