测试方法:
public function convert(AbstractMessage $message)
{
$data = array();
// Text conversion
$text = $message->getText();
if(null !== $text) {
if(!is_string($text) && (is_object($text)
&& !method_exists($text, '__toString'))) {
throw new UnexpectedTypeException(gettype($text), 'string');
}
$data['text'] = (string) $text;
}
}
如何模拟具有__toString
方法的通用对象(无论是哪个类)?
答案 0 :(得分:2)
<?php
// UnderTest.php
class UnderTest
{
public function hasTostring($obj)
{
return method_exists($obj, '__toString');
}
}
// Observer.php
class ObserverTest extends PHPUnit_Framework_TestCase
{
public function testHasTostring()
{
$tester = new UnderTest();
$with = new WithToString();
$without = new WithoutToString();
$this->assertTrue($tester->hasTostring($with));
$this->assertFalse($tester->hasTostring($without));
// this automatically calls to string
// and if the method toString doesnt exists - returns E_RECOVERABLE_ERROR
// so this line should work
$x = $with . '';
// but this shouldnt work, because the method doesnt exist
// therefore you are supposed to get an exception
$this->setExpectedException('PHPUnit_Framework_Error');
$x = $without . '';
}
}
class WithToString
{
public function __toString() { return 'hi'; }
}
class WithoutToString{}