Brian
Brian

Reputation: 7155

How do I mock one method of an interface?

I want to mock the validate method of an interface, and have all the other interface methods stubbed return null (I don't really care what happens to them), but there doesn't appear to be a way to do this easily.

Here's what I have:

    $validator = $this
        ->getMockBuilder('Symfony\Component\Validator\Validator\ValidatorInterface')
        ->setMethods(array('validate'))
        ->getMock();

    $validator
        ->expects($this->once())
        ->method('validate')
        ->willReturn(array());

    $validator->validate();

Running this gives me a fatal error:

Class Mock_ValidatorInterface_56c4c003 contains 6 abstract methods and must therefore be declared abstract or implement the remaining methods

So - I need to somehow tell PHPUnit to stub the other methods that the interface requires. What's the right way to do this?

Upvotes: 7

Views: 797

Answers (1)

mona lisa
mona lisa

Reputation: 389

Declare all the interface's methods in ->setMethods().

Generally, you mock a class and only declare certain methods in ->setMethods(). The un-mocked methods fall back to the implementations on the original class being mocked.

But if you are mocking an interface, all methods must be implemented by the mock.

Upvotes: 5

Related Questions