Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
简单的PHPUnit是关于获取一个通用的模拟对象的_Php_Testing_Mocking_Phpunit - Fatal编程技术网

简单的PHPUnit是关于获取一个通用的模拟对象的

简单的PHPUnit是关于获取一个通用的模拟对象的,php,testing,mocking,phpunit,Php,Testing,Mocking,Phpunit,试验方法: 公共函数转换(AbstractMessage$message) { $data=array(); //文本转换 $text=$message->getText(); 如果(空!==$text){ 如果(!is_string($text)&(is_object($text) &&!方法_存在($text,'.\u toString')){ 抛出新的UnexpectedTypeException(gettype($text),'string'); } $data['text']=(字符串

试验方法:

公共函数转换(AbstractMessage$message)
{
$data=array();
//文本转换
$text=$message->getText();
如果(空!==$text){
如果(!is_string($text)&(is_object($text)
&&!方法_存在($text,'.\u toString')){
抛出新的UnexpectedTypeException(gettype($text),'string');
}
$data['text']=(字符串)$text;
}
}

如何模拟具有
\uu toString
方法的泛型对象(无论是哪个类)?

您不必模拟它。您只需创建一个真实的对象来用于测试。从你的问题中我不明白的是你到底想测试什么。您是否正在尝试测试对象是否具有_utoString方法?您是指空类?我正在测试@ExpectedException是的。但是再一次。你想测试什么?检查类是否具有
\uuuu toString
方法的方法?@Alex。如果它是一个没有字符串的对象,请期待一个意外的TypeException。请参阅我的答案。你能从这里开始吗?把这两个类插入到你的测试文件中。把它们放在那里,而不是试图去模仿一些东西,这没关系。好吧,很好,我想象不出这仅仅是创建一个类:)
<?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{}