diff --git a/src/Expectation.php b/src/Expectation.php index 9491fa6b..5741823f 100644 --- a/src/Expectation.php +++ b/src/Expectation.php @@ -327,6 +327,36 @@ final class Expectation return $this; } + /** + * Asserts that $number matches value's Length. + */ + public function toHaveLength(int $number): Expectation + { + if (is_string($this->value)) { + Assert::assertEquals($number, grapheme_strlen($this->value)); + + return $this; + } + + if (is_iterable($this->value)) { + return $this->toHaveCount($number); + } + + if (is_object($this->value)) { + if (method_exists($this->value, 'toArray')) { + $array = $this->value->toArray(); + } else { + $array = (array) $this->value; + } + + Assert::assertCount($number, $array); + + return $this; + } + + throw new BadMethodCallException('Expectation value length is not countable.'); + } + /** * Asserts that $count matches the number of elements of the value. */ diff --git a/tests/.snapshots/success.txt b/tests/.snapshots/success.txt index 3ff086f1..b819b306 100644 --- a/tests/.snapshots/success.txt +++ b/tests/.snapshots/success.txt @@ -419,6 +419,21 @@ ✓ failures ✓ not failures + PASS Tests\Features\Expect\toHaveLength + ✓ it passes with ('Fortaleza') + ✓ it passes with ('Sollefteå') + ✓ it passes with ('Ιεράπετρα') + ✓ it passes with ('PT-BR 🇵🇹🇧🇷😎') + ✓ it passes with (stdClass Object (...)) + ✓ it passes with (Illuminate\Support\Collection Object (...)) + ✓ it passes with array + ✓ it passes with *not* + ✓ it properly fails with *not* + ✓ it fails with (1) + ✓ it fails with (1.5) + ✓ it fails with (true) + ✓ it fails with (null) + PASS Tests\Features\Expect\toHaveProperty ✓ pass ✓ failures @@ -662,5 +677,5 @@ ✓ it is a test ✓ it uses correct parent class - Tests: 4 incompleted, 9 skipped, 432 passed + Tests: 4 incompleted, 9 skipped, 445 passed \ No newline at end of file diff --git a/tests/Features/Expect/toHaveLength.php b/tests/Features/Expect/toHaveLength.php new file mode 100644 index 00000000..95ad382b --- /dev/null +++ b/tests/Features/Expect/toHaveLength.php @@ -0,0 +1,27 @@ +toHaveLength(9); +})->with([ + 'Fortaleza', 'Sollefteå', 'Ιεράπετρα', 'PT-BR 🇵🇹🇧🇷😎', + (object) [1, 2, 3, 4, 5, 6, 7, 8, 9], + collect([1, 2, 3, 4, 5, 6, 7, 8, 9]), +]); + +it('passes with array', function () { + expect([1, 2, 3])->toHaveLength(3); +}); + +it('passes with *not*', function () { + expect('')->not->toHaveLength(1); +}); + +it('properly fails with *not*', function () { + expect('pest')->not->toHaveLength(4); +})->throws(ExpectationFailedException::class); + +it('fails', function ($value) { + expect($value)->toHaveLength(1); +})->with([1, 1.5, true, null])->throws(BadMethodCallException::class);