Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HowTo PHPUnit assertFunction

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.

like image 959
HexaGridBrain Avatar asked Feb 25 '12 22:02

HexaGridBrain


People also ask

What is assert in PHPUnit?

The assertion methods are declared static and can be invoked from any context using PHPUnit\Framework\Assert::assertTrue() , for instance, or using $this->assertTrue() or self::assertTrue() , for instance, in a class that extends PHPUnit\Framework\TestCase .

What are assert functions?

The assert() function tests the condition parameter. If it is false, it prints a message to standard error, using the string parameter to describe the failed condition. It then sets the variable _assert_exit to one and executes the exit statement.

How do you use assert?

Definition and UsageThe assert keyword is used when debugging code. The assert keyword lets you test if a condition in your code returns True, if not, the program will raise an AssertionError. You can write a message to be written if the code returns False, check the example below.


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.

like image 178
Mike B Avatar answered Sep 30 '22 18:09

Mike B


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));
}
like image 23
Mouna Cheikhna Avatar answered Sep 30 '22 18:09

Mouna Cheikhna