TheWebs
TheWebs

Reputation: 12913

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

Upvotes: 2

Views: 1383

Answers (1)

Trowski
Trowski

Reputation: 469

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.

Upvotes: 4

Related Questions