diff --git a/src/Framework/Constraint/Count.php b/src/Framework/Constraint/Count.php index dfb60ebf81a..5b03b00619e 100644 --- a/src/Framework/Constraint/Count.php +++ b/src/Framework/Constraint/Count.php @@ -22,6 +22,15 @@ class Count extends Constraint */ private $expectedCount; + /** + * Cache the actual count value for use in the failure + * description for things like generators that cannot be + * cloned and can only be iterated once + * + * @var null|int + */ + private $actualCount; + public function __construct(int $expected) { $this->expectedCount = $expected; @@ -41,7 +50,9 @@ public function toString(): string */ protected function matches($other): bool { - return $this->expectedCount === $this->getCountOf($other); + $this->actualCount = $this->getCountOf($other); + + return $this->expectedCount === $this->actualCount; } /** @@ -116,7 +127,7 @@ protected function failureDescription($other): string { return \sprintf( 'actual size %d matches expected size %d', - $this->getCountOf($other), + $this->actualCount ?? 0, $this->expectedCount ); } diff --git a/tests/unit/Framework/Constraint/CountTest.php b/tests/unit/Framework/Constraint/CountTest.php index acd8fdb7b7c..ada85429516 100644 --- a/tests/unit/Framework/Constraint/CountTest.php +++ b/tests/unit/Framework/Constraint/CountTest.php @@ -167,6 +167,32 @@ public function testCountEvaluateReturnsNullWithNonCountableAndNonTraversableOth <<assertCount(4, $generator()); + } catch (ExpectationFailedException $e) { + $this->assertEquals( + <<