3

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?

Jack Vial
  • 2,354
  • 1
  • 28
  • 30
  • What is the issue you are having / what are you asking about specifically? How to create the mock? How to get a fake diff result? Something else? – PeeHaa Jan 12 '15 at 20:08
  • The same way you mock any other php function. If your answer is how to generate the command output when mocking, store real execution results in files and make the mock return those file contents. – gontrollez Jan 12 '15 at 20:37
  • @PeeHaa Ideally what I want to do is test that the command executes as expected. I'm just a bit unsure how to go about it. How would you go about? – Jack Vial Jan 12 '15 at 20:59
  • You can write an integration test that creates a new git repository in /tmp, then commits something, calls your method and check if the result is ok. You would have to change your Migrate::gitDiff so that repo path is configurable or given as an argument (return shell_exec("cd $repo_path; git diff HEAD^ HEAD");) – woru Jan 12 '15 at 21:34
  • 2
    But it's a lot of work and you don't really need to test that git works :P so I would go with gontrollez solution. – woru Jan 12 '15 at 21:41
  • Thanks @woru, I think using an external repo or even a sub-module would be the best solution or just not testing it at all as the command and results are pretty simple but I want to be sure it works. – Jack Vial Jan 12 '15 at 22:48

1 Answers1

6

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.

Piotr Olaszewski
  • 6,017
  • 5
  • 38
  • 65
  • Thanks for taking the time to answer, I'll checkout this library, I'm sure it will come in handy in the future although I've realized that mocking is probably not the best option. But this is still a good answer to my origin question. – Jack Vial Jan 12 '15 at 22:53