diff --git a/plugin/assert/Assert.php b/plugin/assert/Assert.php index e179d16..2c2b96d 100644 --- a/plugin/assert/Assert.php +++ b/plugin/assert/Assert.php @@ -252,6 +252,33 @@ public static function null( )); } + /** + * Asserts that the given value is not null. + * + * @param mixed $actual The actual value to check for non-null. + * @param string $message Short description about what exactly is being asserted. + * @throws AssertionException when the assertion fails. + * + * @psalm-assert !null $actual + * @phpstan-assert !null $actual + */ + #[AssertMethod] + public static function notNull( + mixed $actual, + string $message = '', + ): void { + $actual !== null + ? StaticState::success($actual, 'is not `null`', $message) + : StaticState::fail(new ComparisonFailure( + expected: 'non-null', + actual: $actual, + value: Support::stringify($actual), + assertion: 'is not `null`', + context: $message, + reason: 'expected a non-null value, got `null`', + )); + } + /** * Checks if a value is blank. * diff --git a/plugin/assert/tests/Feature/AssertNotNullTest.php b/plugin/assert/tests/Feature/AssertNotNullTest.php new file mode 100644 index 0000000..532ed52 --- /dev/null +++ b/plugin/assert/tests/Feature/AssertNotNullTest.php @@ -0,0 +1,49 @@ +status, Status::Passed); + } + + #[Test] + public function nullFails(): void + { + $result = TestRunner::runTest([AssertNotNullNegative::class, 'nullFails']); + + Assert::same($result->status, Status::Failed); + Assert::instanceOf($result->failure, Assertion::class); + Assert::string($result->failure->getFailReason()) + ->contains('expected a non-null value, got `null`'); + } + + #[Test] + public function nullFailsWithMessage(): void + { + $result = TestRunner::runTest([AssertNotNullNegative::class, 'nullFailsWithMessage']); + + Assert::same($result->status, Status::Failed); + Assert::instanceOf($result->failure, Assertion::class); + Assert::string($result->failure->getFailReason()) + ->contains('expected a non-null value, got `null`'); + Assert::same($result->failure->getContext(), 'Value must not be null.'); + } +} \ No newline at end of file diff --git a/plugin/assert/tests/Self/AssertNotNull.php b/plugin/assert/tests/Self/AssertNotNull.php new file mode 100644 index 0000000..14986c1 --- /dev/null +++ b/plugin/assert/tests/Self/AssertNotNull.php @@ -0,0 +1,55 @@ +getContext(), 'my context'); + return; + } + Assert::fail('Expected AssertionException to be thrown'); + } + + #[Test] + public function checkObjectIsNotNull(): void + { + Assert::notNull(new \stdClass()); + } +} diff --git a/plugin/assert/tests/Stub/AssertNotNullNegative.php b/plugin/assert/tests/Stub/AssertNotNullNegative.php new file mode 100644 index 0000000..6083f38 --- /dev/null +++ b/plugin/assert/tests/Stub/AssertNotNullNegative.php @@ -0,0 +1,26 @@ +