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();
1
  • I think in this case, you would just test the runTask() method and not test the start() method. Commented Apr 20, 2015 at 23:18

1 Answer 1

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().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.