3

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

2
  • 1
    If you need to make sure parts of your code has a certain visibility, you might be better off using php codesniffer. PHPUnit isnt the right tool for this. Commented May 10, 2011 at 7:32
  • It's perfectly fine to test visibility. I don't see how a codesniffer is the right tool. As far as I see it a codesniffer is the wrong tool. I don't even see how a codesniffer would do what Michael is asking without god only knows what codesniffer configurations. Commented Aug 20, 2016 at 17:41

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly: "You typically don't use unit tests to test your typing ability" and very nice samples +1 :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.