模拟PHP单元中的接口

时间:2015-07-10 14:29:50

标签: php unit-testing

我不确定我做错了什么/。我收到错误:

Configuration read from /vagrant/freya-component-pagebuilder/phpunit.xml

....E........

Time: 50 seconds, Memory: 83.25Mb

There was 1 error:

1) PageSectionTest::testBuildSectionsNotNull
Argument 3 passed to Freya\Component\PageBuilder\PageSection\PageSection::buildSections() must be an instance of Freya\Component\PageBuilder\FieldHandler\IFieldHandler, instance of Mock_IFieldHandler_4f9ceb0e given, called in /vagrant/freya-component
-pagebuilder/tests/PageSectionTest.php on line 58 and defined

/vagrant/freya-component-pagebuilder/Freya/Component/PageBuilder/PageSection/PageSection.php:24
/vagrant/freya-component-pagebuilder/tests/PageSectionTest.php:58
/usr/local/bin/vendor/phpunit/phpunit/src/TextUI/Command.php:151
/usr/local/bin/vendor/phpunit/phpunit/src/TextUI/Command.php:103

FAILURES!
Tests: 13, Assertions: 4, Errors: 1.

Generating code coverage report in HTML format ... done

我的意思是它看起来很明显,但我的测试是嘲笑界面......

public function testBuildSectionsNotNull() {
    $stub = $this->getMockBuilder('IFieldHandler')
                 ->setMethods(array('getFields'))
                 ->getMock();

    $stub->method('getFields')
         ->with(111)
         ->willReturn(array('something' => 'something else'));

    $sections = $this->pageSectionClassInstance->buildSections($this->parentPage, 'child_pages', $stub, '_default_partial');
    $this->assertNotEmpty($section);
}

它知道这存在是因为:

use Freya\Component\PageBuilder\PageSection\PageSection;
use Freya\Component\PageBuilder\FieldHandler\IFieldHandler;
use Freya\Factory\Pattern;

class PageSectionTest extends WP_UnitTestCase { ... }

我试过模拟实现接口的类但是也没有用。参数3是$stub。所以我的问题是:为什么这不起作用?我正在嘲笑一个界面......这个类存在并被看到..

1 个答案:

答案 0 :(得分:1)

您需要将完全限定名称传递给$this->getMockBuilder()。在您的示例中,您需要传递字符串'Freya\Component\PageBuilder\FieldHandler\IFieldHandler'

如果您使用的是PHP 5.5或更高版本,您还可以使用::class魔术常量而不是字符串。在您的示例中,它将是IFieldHandler::class