3

I'm quite new to PHPUnit, and need some advice on how to properly test this Daemon class, start() and runTask() methods.

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);
        }
    }
}

I've tried to use a mock, but it doesn't seem to work.

$mock = $this->getMock('Daemon');
$mock->expects($this->once())->method('runTask');
$mock->start();
Will
  • 24,082
  • 14
  • 97
  • 108
Moefelt
  • 31
  • 1

1 Answers1

1

I would try setting $this->sig to stop before testing the method, allowing it to only run once. You should mainly be concerned about testing $this->runTask(), but I understand wanting better coverage, and testing the break; logic.

The problem is, if the "stop logic" fails, your tests might run forever, so you'll need to set a timelimit for the test suite (see PHPUnit Strict Mode). Timing-out a function call is difficult in PHP (see here), and may need to involve spinning-off a subprocess, but this could be done as well. Try to do as little as possible inside the while loop (even the stop check could be refactored out to a if ($this->shouldStop()) break;, then just test $this->shouldStop() and $this->runTask().

Will
  • 24,082
  • 14
  • 97
  • 108