How can I unit test a PHP class method that executes a command-line program?

Posted by acoulton on Stack Overflow See other posts from Stack Overflow or by acoulton
Published on 2012-04-14T23:12:08Z Indexed on 2012/04/14 23:29 UTC
Read the original article Hit count: 251

Filed under:
|
|
|

For a PHP application I'm developing, I need to read the current git revision SHA which of course I can get easily by using shell_exec or backticks to execute the git command line client.

I have obviously put this call into a method of its very own, so that I can easily isolate and mock this for the rest of my unit tests. So my class looks a bit like this:

class Task_Bundle
{

    public function execute()
    {
        // Do things
        $revision = $this->git_sha();
        // Do more things
    }

    protected function git_sha()
    {
        return `git rev-parse --short HEAD`;
    }
}

Of course, although I can test most of the class by mocking git_sha, I'm struggling to see how to test the actual git_sha() method because I don't see a way to create a known state for it. I don't think there's any real value in a unit test that also calls git rev-parse to compare the results? I was wondering about at least asserting that the command had been run, but I can't see any way to get a history of shell commands executed by PHP - even if I specify that PHP should use BASH rather than SH the history list comes up empty, I presume because the separate backticks executions are separate terminal sessions.

I'd love to hear any suggestions for how I might test this, or is it OK to just leave that method untested and be careful with it when the app is being maintained in future?

© Stack Overflow or respective owner

Related posts about php

Related posts about git