1

测试方法:

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方法的通用对象(无论类)?

4

1 回答 1

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{}
于 2012-11-20T17:43:39.213 回答