
Write Deterministic PHPUnit Assertions with Mockery::capture
Originally published at recca0120.github.io How do you write assertions when a method internally generates a random value, making the return value unpredictable? Random Values Make Tests Unpredictable Suppose we have a RandomHash class that generates a random number between 1 and 10, then hashes it: class Hash { public function make ( $data ): string { return hash_hmac ( 'sha256' , $data , false ); } } class RandomHash { public function __construct ( public Hash $hash ) { } /** * @throws \Exception */ public function hash (): string { $random = md5 ( random_int ( 1 , 10 )); return $this -> hash -> make ( $random ); } } Since random_int returns a different value each time, the result of hash() changes too, making it impossible to write a definitive expected value: class RandomHashTest extends TestCase { public function test_mockery_capturing_arguments (): void { $hash = new Hash (); $randomHash = new RandomHash ( $hash ); // no way to write a definitive assertion here $actual = $randomH
Continue reading on Dev.to
Opens in a new tab


