Sand Box: A first class API that allows unit testing of code with mocks
and stubs of other classes or functions, without the need to modify the
class under test.

This is an initial idea of how a Sand Box API could work:

$oSandbox = new SPLSandBox();

$oSandbox->MockFunction('\mocks\fopen','\fopen');
$oSandbox->MockFunction('\mocks\fread','\fread');
$oSandbox->MockFunction('\mocks\fwrite','\fwrite');
$oSandbox->MockFunction('\mocks\fclose','\fclose');

$oFileManager = $oSandbox->GetInstance('MyFileManager');

$oFileManager->WriteFile('/path/to/file.txt');


Let's break down what's happening:

The call to `new SPLSandBox();` creates a sandbox instance.

When we then call `$oSandbox->MockFunction()`, we specify the name of a
function that's generally available to the PHP application, and also
specify the name of that function as it should appear to code running
inside the sandbox.

In this case, we have told the sandbox that any call to \fopen, \fread,
\fwrite, or \fclose by sandboxed code should be remapped to
\mocks\fopen, \mocks\fread, \mocks\fwrite, and \mocks\fclose.

The code in the sandbox is completely unaware of this and remains
unchanged.

The line:

$oFileManager = $oSandbox->GetInstance('MyFileManager');

Creates a **sandboxed** instance of the MyFileManager class.

$oFileManager is exactly the same as it normally is, but any calls it
makes to a function will use the Mock function instead, if defined by
`MockFunction()`, or will simply fail if no mock has been loaded into
the sandbox.

We then tell the sandboxed instance of the MyFileManager class to write
out a file.

The `MyFileManager::WriteFile()` method calls to `\fopen`, `\fwrite`,
and `\fclose`.

But, unknown to MyFileManager, the sandbox has remapped those calls to
the mock functions we specified instead.

If you know how a chroot jail works on Linux, this will seem very
familiar. Pass in all the dependencies the class under test needs,
remapped to stubs, then get a sandboxed instance of the class to test
with.

Reply via email to