如何PHPUnit测试一个没有返回值的方法?

时间:2014-12-16 18:34:23

标签: php unit-testing phpunit

我正在尝试从我编写的以下类中测试方法(函数比显示的更多,基本上,每个函数都是_ *()方法):

class Validate {
  private static $initialized = false;

  /**
  * Construct won't be called inside this class and is uncallable from the outside. This prevents
  * instantiating this class. This is by purpose, because we want a static class.
  */
  private function __construct() {}

  /**
  * If needed, allows the class to initialize itself
  */
  private static function initialize()
  {
    if(self::$initialized) {
      return;
    } else {
      self::$initialized = true;
      //Set any other class static variables here
    }
  }

  ...

  public static function isString($string) {
    self::initialize();
    if(!is_string($string)) throw new InvalidArgumentException('Expected a string but found ' . gettype($string));
  }

  ...

}

当我测试方法是否在无效输入上抛出异常时,它的效果很好!但是,当我测试方法是否按预期工作时,PHPUnit会抱怨因为我在测试中没有断言。具体错误是:

# RISKY This test did not perform any assertions

但是,我没有任何价值可以断言,所以我不知道如何克服这一点。

我已经阅读了一些关于测试静态方法的内容,但这似乎主要涵盖了静态方法之间的依赖关系。此外,即使是非静态方法也没有返回值,那么,如何解决这个问题?

供参考,我的测试代码:

class ValidateTest extends PHPUnit_Framework_TestCase {
  /**
  * @covers ../data/objects/Validate::isString
  * @expectedException InvalidArgumentException
  */
  public function testIsStringThrowsExceptionArgumentInvalid() {
    Validate::isString(NULL);
  }

  /**
  * @covers ../data/objects/Validate::isString
  */
  public function testIsStringNoExceptionArgumentValid() {
    Validate::isString("I am a string.");
  }
}

4 个答案:

答案 0 :(得分:4)

基于example 2.12 from chapter 2 of PHPUnit,我遇到的一个解决方案如下。对我来说这感觉有点哈哈,但它是迄今为止我发现的最好的。此外,根据这个PHPUnit Gitub issue discussion,似乎有其他人想要这个功能但是没有计划实现它。

将testIsStringNoExceptionArgumentValid()更改为以下内容:

  /**
  * @covers ../data/objects/Validate::isString
  */
  public function testIsStringNoExceptionArgumentValid() {
    try {
      Validate::isString("I am a string.");
    } catch (InvalidArgumentException $notExpected) {
      $this->fail();
    }

    $this->assertTrue(TRUE);
  }

答案 1 :(得分:4)

使用assertNull测试无效功能:

    /**
     * @covers ../data/objects/Validate::isString
     */
    public function testIsStringNoExceptionArgumentValid() {
         $this->assertNull( Validate::isString("I am a string.") );
    }

答案 2 :(得分:4)

要防止有关断言的警告,您可以使用@doesNotPerformAssertions注释,如文档中所述:https://phpunit.de/manual/current/en/appendixes.annotations.html#idp1585440

或者如果您更喜欢代码而不是注释: $this->doesNotPerformAssertions();

答案 3 :(得分:0)

如果你想测试一个 void 函数,你只需要在没有任何断言的情况下运行它。 如果有任何问题,它将抛出异常并且测试将失败。无需输入 $this->assertTrue(TRUE);,因为您没有运行断言,并且不需要断言来测试您的代码。

你会收到类似的消息


Time: 7.39 seconds, Memory: 16.00 MB

OK (1 test, 0 assertions)
Process finished with exit code 0
相关问题