I have an interesting problem and have searched the internet, but haven't yet found an answer.

Consider the following function:

function get_setting_values_from_file( $parameter )
{
    exec("/usr/var/binary --options $parameter", $output, $return);
    $settings = file( $output[0] );
}

I need to unit test a similar function. I am currently using phpUnit for my tests and the vfsStream libraries to mock the file system, but how do you mock the binary file available on the system or what is the recommend approach for dealing with test cases like this?

All feedback is appreciated.

Recommended Answers

All 2 Replies

Member Avatar for LastMitch

How do you mock a binary file execution for unit tests with phpUnit?

Does that code you provided work? You can used this instead/try:

http://docs.moodle.org/dev/PHPUnit

I devised a solution to my problem with a little bit of research.

The exec command is a standard php function. The binary file that I'm trying to mock is available on the production system, but is not available on the development system. My goal is to mock the output of the file, that being the case I used php namespaces to solve my problem.

//a name space used so that php functions can be mocked any namespace name is okay
namespace VirtualSystem {
    function exec($command, &$output, &$return)
    {
        //assign values in a similar way as the real binary file would
        $output[0] = "vfs://var/tmp/random_directory"; //this works if a vfsstream is setup
        //the binary ran just fine
        $return = 0;
    }

    //this function will now call the exec function defined in
    //this namespace instead of the standard php function 
    function get_setting_values_from_file( $parameter )
    {
        exec("/usr/var/binary --options $parameter", $output, $return);
        $settings = file( $output[0] );
    }
}
//the standard global php namespace
namespace {
   class SqlColumnTest extends PHPUnit_Framework_TestCase
   {
       /**
       * @test
       */
       public function getSettingValuesFunction()
       {
           //i can call the function here like this for testing
           VirtualSystem\get_setting_values_from_file( "a_value" );

           //if i change the function so that it
           //returns something to be evaluated, i can run some asserts here
           //however the point is i have now made a mock of the exec function
           //and i can test it as needed
       }
   }
}

I think that this is a great way to mock and test the return values from standard PHP functions when you don't have access to the resources avalable on the real system.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.