<?php | |
/** | |
* Stubs a method by returning a user-defined value. | |
*/ | |
class ReturnValue implements PHPUnit_Framework_MockObject_Stub | |
{ | |
protected $value; | |
public function __construct($value) | |
{ | |
$this->value = $value; | |
} | |
public function invoke(PHPUnit_Framework_MockObject_Invocation $invocation) | |
{ | |
$annotations = PHPUnit_Util_Test::parseTestMethodAnnotations($invocation->className, $invocation->methodName); | |
if (!isset($annotations['method']['return'][0])) { | |
throw new PHPUnit_Framework_Exception('Invalid method declaration; return type required'); | |
} else { | |
$actual = strtolower(gettype($this->value)); | |
$expected = explode('|', $annotations['method']['return'][0]); | |
if (count($expected) > 1) { | |
throw new PHPUnit_Framework_Exception( | |
sprintf( | |
'%s cannot return more than one type, %d given (%s)', | |
$invocation->methodName, | |
count($expected), | |
implode(', ', $expected) | |
) | |
); | |
} elseif (!in_array($actual, $expected)) { | |
throw new PHPUnit_Framework_Exception( | |
sprintf( | |
'%s does not match expected type "%s"', | |
$actual, | |
$annotations['method']['return'][0] | |
) | |
); | |
} | |
} | |
return $this->value; | |
} | |
public function toString() | |
{ | |
return sprintf('return user-specified value %s', PHPUnit_Util_Type::export($this->value)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment