Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit Test to assert if a function/var is public private or protected?

Tags:

phpunit

Is there a way to assert if a method or variable is public private or protected with phpunit?

like image 931
Michael Avatar asked Aug 27 '26 06:08

Michael


1 Answers

PHPUnit doesn't provide those assertions, and you typically don't use unit tests to test your typing ability. They should validate that the code works at runtime. Here are more pointless unit tests:

  • Assert that the class is named CorrectClassName.
  • Assert that function foo() { return 5; } returns 5.
  • Assert that function comments don't contain the word "winning".

Now, sometimes you just want to do something even when it's not recommended or has little value. I know I do. :) Add this to your base test case class:

/**
 * Assert that a method has public access.
 *
 * @param string $class name of the class
 * @param string $method name of the method
 * @throws ReflectionException if $class or $method don't exist
 * @throws PHPUnit_Framework_ExpectationFailedException if the method isn't public
 */
function assertPublicMethod($class, $method) {
    $reflector = new ReflectionMethod($class, $method);
    self::assertTrue($reflector->isPublic(), 'method is public');
}

Completing assertProtectedMethod() and assertPrivateMethod() are left as an exercise. You can do the same thing for properties, and you could even make this method more generic to handle a method or property--whichever is found--and throw some other error if neither exist.

like image 122
David Harkness Avatar answered Aug 30 '26 08:08

David Harkness



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!