使用克隆对象时的PHPUnit ReturnCallback

时间:2014-06-24 11:20:48

标签: php callback phpunit clone

我发现修改由我正在测试的类克隆的模拟对象非常困难。 这是我的测试:

    $firstDocument = array('type' => 'venue', 'name'=> "first venue");

    $venueContent = $this->getMockBuilder('My\Class\Namespace\VenueContent')->disableOriginalConstructor()->getMock();

    $setValues = function($document) use(&$venueContent){
        $venueContent->expects($this->any())->method('getDocument')->will($this->returnValue($document));
        $venueContent->expects($this->any())->method('getName')->will($this->returnValue($document->name));
    };

    $venueContent->expects($this->any())->method('setDocument')->will($this->returnCallback($setValues));

    $this->object = new ContentFactory();
    $this->object->registerContentType('venue', $venueContent);

    $firstVenue = $this->object->create($firstDocument);

这是ContentFactory类:

class ContentFactory
{
/**
 * @var array classMap
 */
private $contentTypes = array();

/**
 * Register a document map for use in creating & validating documents
 * @param string $name
 * @param array $type
 */
public function registerContentType($name, $type)
{
    $this->contentTypes[$name] = $type;
}

/**
 * Create & validate a document
 * @param array $document
 * @throws \InvalidArgumentException
 * @return ContentInterface
 */
public function create(array $document)
{
    if (!isset($document['type'])) {
        throw new \InvalidArgumentException('Unknown content type');
    }
    $documentType = $document['type'];

    if (!\array_key_exists($documentType, $this->contentTypes)) {
        throw new \InvalidArgumentException('Unmapped content service');
    }
    $contentModel = clone $this->contentTypes[$documentType];
    $contentDocument = $this->createContentDocument($document);

    $contentModel->setDocument($contentDocument);

    return $contentModel;
}

/**
 * Create underlying ContentDocument
 * @param array $document
 * @return ContentDocument
 */
private function createContentDocument($document)
{
    return new ContentDocument($document);
}
}

我的问题是,每当我执行对象的clone时,我都无法在测试的回调中修改它,因为我在USE语句中传递的对象是原始对象(我使用的对象)克隆)。 有没有人知道回调如何访问调用者对象,以便我可以修改它,无论它是什么实例而不使用debug_backtrace

0 个答案:

没有答案
相关问题