假設有個 class:
class Woker { protected Queue $queue; public function run() { while (!$this->queue->isEmpty()) { $job = $this->queue->pop(); // do something } } }
用 PHPUnit 建立 stub 以後,必須使用 reflection 來自訂 $queue
property:
$worker = $this->getMockBuilder(Worker::class) ->disableOriginalConstructor() ->getMock(); $queue = $this->createMock(Queue::class); $queue->expected($this->atLeast(1)) ->method('isEmpty') ->willReturn(true); // PHP Reflection on $worker $refProperty = new \ReflectionProperty($worker, 'queue'); $refProperty->setAccessible(true); $refProperty->setValue($crawler, $queue);
這樣寫 test case 蠻髒的,有點想要換 test framework ….