Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decouple or mock?

Suppose I have this class:

class SomeClass
{
    // Top level function
    public function execute($command)
    {
        // Get output from system tool
        $output = $this->runTool($command);

        // Check output for errors
        if ($this->hasError($output))
            return false;

        // And parse success response from tool
        return $this->parseOutput($output);
    }

    // There we're make a call to system
    private function runTool($command)
    {
        return `/some/system/tool $command`;
    }
    [...]
}

I do not want to run system tool in my test, I want to replace a system call with predefined output.

So, the question is - should I create another class, move system call in it and mock that class in the test, or I can mock only that function of class which I will test?

Sure, both approaches will work, but which of them will be serve testing purposes better?

like image 247
Neka Avatar asked Nov 28 '25 11:11

Neka


1 Answers

If you follow the single responsibility principle, you won't have this problem. Your class does not need to know how system calls are made, so you will have to use another class. You mock that.

IMO, in most cases when you need to mock protected or private methods, they do stuff that should be into another class and be mocked.

like image 67
gontrollez Avatar answered Nov 30 '25 00:11

gontrollez