0

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.

Edited by nexocentric: $output becomes an array

2
Contributors
2
Replies
22
Views
4 Years
Discussion Span
Last Post by nexocentric
1

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.

Edited by nexocentric: Explained how I came up with the solution.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.