Jack Jack - 2 months ago 8
PHP Question

How can I mock the results of git diff in phpunit

I'm writing a database migration script in PHP and I need to mock the results of a git diff in phpunit.
The idea is that the git diff will only return the names of files that have been added or updated in includes/ since the previous commit. But of course this is going to keep changing as I'm working on the script and committing my changes.

Here is the Migrate class and gitDiff method:

#!/usr/bin/php
<?php

class Migrate {

public function gitDiff(){
return shell_exec('git diff HEAD^ HEAD --name-only includes/');
}
}
?>


Any ideas?

Answer

In PHPUnit:

$mock = $this->getMockBuilder('Migrate')
                     ->setMethods(array('getDiff'))
                     ->getMock();

$mock->expects($this->any())
        ->method('getDiff')
        ->will($this->returnValue('your return'));

$this->assertEquals("your return", $mock->getDiff());

You can use ouzo goodies mock tool:

$mock = Mock::create('Migrate');

Mock::when($mock)->getDiff()->thenReturn('your return');

$this->assertEquals("your return", $mock->getDiff());

All docs here.

Comments