如何PHPUnit断言功能

时间:2012-02-25 22:56:41

标签: php function phpunit assert

我想知道如何验证“类”是否具有函数。 assertClassHasAttribute不起作用,这是正常的,因为Function不是Attribute。

2 个答案:

答案 0 :(得分:35)

当PHPUnit没有提供断言方法时,我要么创建它,要么使用一个带有详细消息的低级断言:

$this->assertTrue(
  method_exists($myClass, 'myFunction'), 
  'Class does not have method myFunction'
);

assertTrue()是最基本的。它允许很大的灵活性,因为你可以使用任何内置的php函数来为你的测试返回一个bool值。因此,当测试失败时,错误/失败消息根本没有用。像Failed asserting that <FALSE> is TRUE这样的东西。这就是为什么将第二个参数传递给assertTrue()来详细说明测试失败的原因很重要。

答案 1 :(得分:7)

  

单元和集成测试用于测试不用于重述的行为   类的定义是什么。

因此PHPUnit不提供这样的断言。 PHPUnit可以断言一个类有一个名字X,一个函数返回值somthing,但你可以用你想做的事情:

/**
 * 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));
}