3

I have a unit test that checks that an exception is thrown if the openssl_random_pseudo_bytes is not installed. However, if it is installed, it currently gets skipped. This is unsatisfactory to me, though, as it results in an imperfect test run. I could set the unit test to pass, but that feels like a cheat.

Does anyone have any ideas?

Here is my test as it stands:

public function testGenerateOpenSSLThrowsExceptionWhenFunctionDoesNotExist()
{
    if (function_exists('openssl_random_pseudo_bytes')) {
        $this->markTestSkipped('Cannot run test: openssl_random_pseudo_bytes function exists.');
    }

    $this->_salt->generateFromOpenSSL();
}
Thomas Marchant
  • 208
  • 4
  • 14

1 Answers1

4

Not directly, but you could mock function_exists with a little trick as described in Can I "Mock" time in PHPUnit?

Prerequisites

  • the class under test (CUT) is in a PHP namespace
  • function_exists() is called with its unqualified name (i.e. not as \function_exists())

Example

Let's say, the CUT looks like this:

namespace Stack;
class Salt
{
    ...
        if (function_exists('openssl_random_pseudo_bytes'))
    ...
}

Then this is your test, in the same namespace:

namespace Stack;

function function_exists($function)
{
    if ($function === 'openssl_random_pseudo_bytes') {
        return SaltTest::$opensslExists;
    }
    return \function_exists($function);
}

class SaltTest extends \PHPUnit_Framework_Test_Case
{
    public static $opensslExists = true;

    protected function setUp()
    {
        self::$opensslExists = true;
    }

    public function testGenerateOpenSSLThrowsExceptionWhenFunctionDoesNotExist()
    {
        self::$opensslExists = false;
        $this->_salt->generateFromOpenSSL();
    }

}

The namespaced function will take precedence over the core function and delegate to it for all parameters, except 'openssl_random_pseudo_bytes'.

If your tests live in a different namespace, you can define multiple namespaces per file like this:

namespace Stack
{
    function function_exists($function)
    ...
}
namespace StackTest
{
    class SaltTest extends \PHPUnit_Framework_Test_Case
    ...
}
Community
  • 1
  • 1
Fabian Schmengler
  • 24,155
  • 9
  • 79
  • 111