【问题标题】:How to setup phpunit tests for a php daemon如何为 php 守护进程设置 phpunit 测试
【发布时间】:2015-03-14 10:48:05
【问题描述】:

我是 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();

【问题讨论】:

  • 我认为在这种情况下,您只需测试runTask() 方法而不测试start() 方法。

标签: php mocking phpunit


【解决方案1】:

我会在测试方法之前尝试将$this->sig 设置为stop,让它只运行一次。您应该主要关心测试$this->runTask(),但我知道想要更好的覆盖范围,并测试break; 逻辑。

问题是,如果“停止逻辑”失败,您的测试可能会永远运行,因此您需要为测试套件设置时间限制(请参阅PHPUnit Strict Mode)。在 PHP 中让函数调用超时是很困难的(请参阅here),并且可能需要涉及拆分子进程,但也可以这样做。尝试在 while 循环中做尽可能少的事情(即使停止检查也可以重构为 if ($this->shouldStop()) break;,然后只需测试 $this->shouldStop()$this->runTask()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-03
    • 1970-01-01
    • 2012-10-17
    • 2012-06-23
    • 2023-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多