php - PHP 单元中的模拟接口(interface)

标签 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

我的意思是这看起来很明显,但我的测试是模拟接口(interface)......

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

我尝试模拟实现接口(interface)的类,但这也不起作用。参数三是$stub。所以我的问题是:为什么这不起作用?我正在 mock 一个接口(interface)...该类存在并且可见..

最佳答案

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

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

关于php - PHP 单元中的模拟接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31343381/

相关文章:

PHP:mcrypt 与非对称 openssl 用于加密两方之间的消息

php - bind_param 中未知数量的参数

c# - 测试此任务的正确方法是什么?

unit-testing - react 堆项目 : wait while broadcaster finish

javascript - 返回 false 后提交表单

PHP STMT MySQL 查询在设置为等于时返回 LIKE 结果

php - AJAX POST 无法在 DIV 中加载 PHP 页面

ruby-on-rails - 测试时我应该在 Factory girl 中 stub 模型还是在规范文件中 stub ?

android - 已弃用属性的 Gradle 警告

javascript - Jest 模拟特定的配置值