I was wondering if how I can verify if a 'class' has a Function. assertClassHasAttribute does not work, it's normal since a Function is not an Attribute.
-
2why would you want to test that?Gordon– Gordon2012-02-25 23:34:33 +00:00Commented Feb 25, 2012 at 23:34
-
It's useful when I do some refactoring... Having to KNOW, by tests, the methods my classes contain helps when I have to transfert a method into another class for some reasons: like for decoupling responsabilities, etc.HexaGridBrain– HexaGridBrain2012-02-26 02:35:55 +00:00Commented Feb 26, 2012 at 2:35
-
I'd argue that you will never have a need for this when you just make sure the dependencies are properly mocked/stubbed and you have your public API fully covered.Gordon– Gordon2012-02-26 10:51:53 +00:00Commented Feb 26, 2012 at 10:51
2 Answers
When there's not an assertion method provided by PHPUnit I either create it or use one of the lower-level assertions with a verbose message:
$this->assertTrue(
method_exists($myClass, 'myFunction'),
'Class does not have method myFunction'
);
assertTrue() is as basic as you can get. It allows a great deal of flexibility because you can use any built-in php function that returns a bool value for your test. Consequently, when the test fails the error/failure message isn't helpful at all. Something like Failed asserting that <FALSE> is TRUE. That's why it's important to pass the second param to assertTrue() detailing why the test failed.
Comments
Unit and Integration tests are for testing behaviors not for restating what the class definition is.
So PHPUnit doesn't provide such assertion. PHPUnit can either assert that a class has a name X , that a function returns value somthing , but you can do what you want using :
/**
* Assert that a class has a method
*
* @param string $class name of the class
* @param string $method name of the searched method
* @throws ReflectionException if $class don't exist
* @throws PHPUnit_Framework_ExpectationFailedException if a method isn't found
*/
function assertMethodExist($class, $method) {
$oReflectionClass = new ReflectionClass($class);
assertThat("method exist", true, $oReflectionClass->hasMethod($method));
}