简体   繁体   中英

Mocking Interfaces in PHP Unit

I am not sure what I am doing wrong/. I get the error:

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

I mean it seems pretty obvious but my test is mocking the 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);
}

It knows this exists because:

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

class PageSectionTest extends WP_UnitTestCase { ... }

I tried mocking the class that implements the Interface but that didnt work either. Argument three is the $stub . So my question is: Why doesn't this work? I am mocking an interface ... The class exists and is seen ..

You need to pass the fully-qualified name to $this->getMockBuilder() . In your example you need to pass the string 'Freya\\Component\\PageBuilder\\FieldHandler\\IFieldHandler' .

If you're using PHP 5.5 or later, you can also use the ::class magic constant instead of a string. In your example it would be IFieldHandler::class .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM