我对 PHPUnit 很陌生,需要一些关于如何正确测试这个Daemon
类、start()
和runTask()
方法的建议。
class Daemon {
public function start() {
// Start the loop
while (true) {
// This is the code you want to loop during the service...
$this->runTask();
// If signaled to stop
if ('stop' == $this->sig) {
// Break the loop
break;
}
// Now before we 'Task' again, we'll sleep for a bit...
usleep($this->delay);
}
}
}
我尝试使用模拟,但它似乎不起作用。
$mock = $this->getMock('Daemon');
$mock->expects($this->once())->method('runTask');
$mock->start();
我会尝试在测试方法之前将$this->sig
设置为 stop
,允许它只运行一次。您应该主要关注测试$this->runTask()
,但我理解想要更好的覆盖范围并测试break;
逻辑。
问题是,如果"停止逻辑"失败,您的测试可能会永远运行,因此您需要为测试套件设置时间限制(请参阅 PHPUnit 严格模式)。在PHP中,对函数调用进行计时是很困难的(见这里),并且可能需要涉及剥离子进程,但这也可以完成。尝试在while循环中尽可能少地做(甚至停止检查也可以重构为if ($this->shouldStop()) break;
,然后只需测试$this->shouldStop()
并$this->runTask()
。