如何用PHPUnit测试没有返回值的方法

如何用PHPUnit测试没有返回值的方法

本文介绍了如何用PHPUnit测试没有返回值的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to test methods from the following class I have written (there are more functions than what is shown, basically, one function for each is_*() method):

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会抱怨,因为我在测试中没有断言.具体错误是:

When I test if the methods throw an exception on invalid input, it works great! However, when I test if the method works as expected, PHPUnit complains because I have no assert in the test. The specific error is:

# RISKY This test did not perform any assertions

但是,我没有任何价值可言,因此我不确定如何克服这一点.

However, I don't have any value to assert against so I'm not sure how to overcome this.

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

I've read some about testing static methods, but that mostly seems to cover dependencies between static methods. Further, even non-static methods could have no return value, so, how to fix this?

供参考,我的测试代码:

For reference, my test code:

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.");
  }
}

推荐答案

要避免出现有关断言的警告,可以按照文档中的说明使用@doesNotPerformAssertions批注: https://phpunit.de/manual/current/en/appendixes.annotations.html#idp1585440

To prevent the warning about the assertions you can use the @doesNotPerformAssertions annotation as explained in the documentation: https://phpunit.de/manual/current/en/appendixes.annotations.html#idp1585440

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

Or if you prefer code over annotation:$this->doesNotPerformAssertions();

这篇关于如何用PHPUnit测试没有返回值的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 22:52