diff --git a/src/PendingCalls/TestCall.php b/src/PendingCalls/TestCall.php index 7dca121b..82dd4b65 100644 --- a/src/PendingCalls/TestCall.php +++ b/src/PendingCalls/TestCall.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace Pest\PendingCalls; use Closure; +use InvalidArgumentException; use Pest\Factories\Covers\CoversClass; use Pest\Factories\Covers\CoversFunction; use Pest\Factories\Covers\CoversNothing; @@ -171,6 +172,31 @@ final class TestCall return $this; } + /** + * Sets the covered classes or methods. + */ + public function covers(string ...$classesOrFunctions): TestCall + { + foreach ($classesOrFunctions as $classOrFunction) { + $isClass = class_exists($classOrFunction); + $isMethod = function_exists($classOrFunction); + + if (!$isClass && !$isMethod) { + throw new InvalidArgumentException( + sprintf('No class or method named "%s" has been found.', $classOrFunction) + ); + } + + if ($isClass) { + $this->coversClass($classOrFunction); + } else { + $this->coversFunction($classOrFunction); + } + } + + return $this; + } + /** * Sets the covered classes. */ diff --git a/tests/Features/Covers.php b/tests/Features/Covers.php index f52d0740..b41b3f8a 100644 --- a/tests/Features/Covers.php +++ b/tests/Features/Covers.php @@ -1,18 +1,24 @@ getAttributes(); @@ -36,8 +42,6 @@ it('uses the correct PHPUnit attribute for nothing', function () { it('removes duplicated attributes', function () { $attributes = (new ReflectionClass($this))->getAttributes(); - expect($attributes)->toHaveCount(7); // 3 classes, 3 functions, 1 nothing - expect($attributes[3]->getName())->toBe('PHPUnit\Framework\Attributes\CoversClass'); expect($attributes[3]->getArguments()[0])->toBe('P\Tests\Features\TestCoversClass2'); expect($attributes[4]->getName())->toBe('PHPUnit\Framework\Attributes\CoversClass'); @@ -50,3 +54,18 @@ it('removes duplicated attributes', function () { ->coversClass(TestCoversClass2::class, TestCoversClass1::class, Covers::class) ->coversNothing() ->coversFunction('bar', 'foo', 'baz'); + +it('guesses if the given argument is a class or function', function () { + $attributes = (new ReflectionClass($this))->getAttributes(); + + expect($attributes[7]->getName())->toBe('PHPUnit\Framework\Attributes\CoversClass'); + expect($attributes[7]->getArguments()[0])->toBe('P\Tests\Features\TestCoversClass3'); + expect($attributes[8]->getName())->toBe('PHPUnit\Framework\Attributes\CoversFunction'); + expect($attributes[8]->getArguments()[0])->toBe('testCoversFunction'); +})->covers(TestCoversClass3::class, 'testCoversFunction'); + +it('throws exception if no class nor method has been found', function () { + $testCall = new TestCall(TestSuite::getInstance(), 'filename', 'description', fn () => 'closure'); + + $testCall->covers('fakeName'); +})->throws(InvalidArgumentException::class, 'No class or method named "fakeName" has been found.');