【问题标题】:Simple PHPUnit one about getting a generic mocked object关于获取通用模拟对象的简单 PHPUnit 之一
【发布时间】:2012-11-08 20:16:33
【问题描述】:

测试方法:

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

【问题讨论】:

  • 你不必嘲笑它。您可以创建自己的真实对象以在测试中使用。我从你的问题中不明白的是你到底想要测试什么。您是否尝试测试对象是否具有 __toString 方法?
  • 你是说空班吗?我正在测试@expectedException
  • 是的。但又一次。你想测试什么?检查类是否有__toString方法的方法?
  • @Alex 完全正确。如果它是一个没有 __toString 的对象,预计会出现 UnexpectedTypeException。
  • 看我的回答。你能从那里开始吗?

标签: php testing mocking phpunit


【解决方案1】:
<?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{}

【讨论】:

  • 只需将这两个类添加到您的测试文件中。可以让它们在那里而不是试图模拟某些东西。
  • 好吧,想不到创建一个类这么简单:)
猜你喜欢
  • 1970-01-01
  • 2011-03-09
  • 2013-09-12
  • 2021-10-31
  • 2012-09-26
  • 1970-01-01
  • 2017-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多