gpt4 book ai didi

php - 关于获取通用模拟对象的简单 PHPUnit 之一

转载 作者:行者123 更新时间:2023-11-28 20:32:29 25 4
gpt4 key购买 nike

测试方法:

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

最佳答案

<?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{}

关于php - 关于获取通用模拟对象的简单 PHPUnit 之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13478703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com