How to create a double for an interface, usefully, concisely and legally?

Viewed 75

I want to create a test double for an interface. The solution must satisfy ALL of the following requirements:

  • MUST allow me to specify custom configurations for SOME methods of the interface
  • MUST automatically stub all REMAINING methods with a default stub
  • MUST NOT require me to explicitly list the remaining methods for which I want a default stub
  • MUST NOT require me to use deprecated APIs like setMethodsExcept([])

Is this currently achievable in a modern PHPUnit (8+), or is it the case that some of the above requirements must be relaxed?

1 Answers

TL;DR: Just Don't Set Any Methods.

$mock = $this->getMockBuilder(MyInterface::class)->getMock();

// That's. Freakin. IT.

$mock->expects($this-any())
    ->method('whatever_but_present_in_interface')
    ->willReturnCallback(function(){ return "YISS!"; });

// It. Just. Works.

With so much talk in the PHPUnit world about configuring your mocks, and with the copious proliferation of APIs for configuring mocked methods in PHPUnit 8 and 9, one might be forgiven for thinking that SOME way of "setting" methods is mandatory, that these APIs somehow "declare" methods you want to mess with, and PHPUnit won't let you mess with them if you don't "declare" them.

Well, no.

Related