php - How to test function that uses rand()?

I have a function that utilises the rand() function and I would like to unit test it... But I'm struggling.

I am currently using Phockito to help with mocking and mock returns etc

public function myFunction()
{
    return hash(
      'sha256', 
      'this is some random string: ' . rand()
    );
}

Test file:

public testFunction()
{
    $myClass = new MyClass();
    $result = $myClass->myFunction();
    $expected = /* Some hashed string I expect */;

    $this->assertEquals($expected, $result);
}

I have thought about trying to Phockito::mock the class I'm working with, but all of the other functions that are connected in this process will be required to be mocked also... And that will be a lot of work.

Answer

Solution:

Either use a library like php-mock to mock php functions or refactor your function to accept your random as an argument like:

public function myFunction($rand = null) {
  $rand = $rand ?? rand();
  // ...
}

Source