【问题标题】:How do I assert the result is an integer in PHPUnit?如何断言结果是 PHPUnit 中的整数?
【发布时间】:2014-03-06 10:28:05
【问题描述】:

我希望能够测试结果是一个整数 (1,2,3...),其中函数可以返回任何数字,例如:

$new_id = generate_id();

我原以为会是这样的:

$this->assertInstanceOf('int', $new_id);

但我收到此错误:

PHPUnit_Framework_Assert::assertInstanceOf() 的参数 #1 必须是类或接口名称

【问题讨论】:

  • 由于通常 ids 不应该为零,您可能还需要检查: 0

标签: php unit-testing phpunit


【解决方案1】:
$this->assertInternalType("int", $id);

编辑:截至PHPUnit 8,答案是:

$this->assertIsInt($id);

【讨论】:

  • @Andrew 我没有测试它的环境。能否请您尝试并分享结果。
  • @Andrew 你现在可能已经明白了。 “34”不起作用
  • 因为“34”的类型其实是字符串,是正常的
  • assertIsInt 方法被添加到版本7.5
【解决方案2】:

我更喜欢使用官方的 PHPUnit 类常量。

PHPUnitv5.2:

use PHPUnit_Framework_Constraint_IsType as PHPUnit_IsType;

// ...

$this->assertInternalType(PHPUnit_IsType::TYPE_INT, $new_id);

或者在撰写本文时最新的是v7.0

use PHPUnit\Framework\Constraint\IsType;

// ...

$this->assertInternalType(IsType::TYPE_INT, $new_id);

【讨论】:

    【解决方案3】:

    下面给出了原始答案以供后代使用,但我强烈建议使用assertInternalType(),如其他答案中所建议的那样。


    原答案:

    只需将 assertTrue 与 is_int() 一起使用。

    $this->assertTrue(is_int($new_id));
    

    【讨论】:

    • 在创建测试时,建议使用最具体的测试用例。这将产生更好的描述性错误。
    【解决方案4】:

    我认为最好使用这种结构:

    $this->assertThat($new_id, $this->logicalAnd(
        $this->isType('int'), 
        $this->greaterThan(0)
    ));
    

    因为它不仅会检查 $new_id 变量的类型,还会检查这个变量是否大于 0(假设 id 不能为负或零),这样更加严格和安全。

    【讨论】:

      【解决方案5】:

      从 PHPUnit 8 开始,其他方法现已弃用,assertInternalType() 现在将抛出此错误并失败:

      assertInternalType() 已弃用并将在 PHPUnit 9 中删除。重构您的测试以使用 assertIsArray()、assertIsBool()、assertIsFloat()、assertIsInt()、assertIsNumeric()、assertIsObject()、assertIsResource()、assertIsString ()、assertIsScalar()、assertIsCallable() 或 assertIsIterable()。

      现在建议为此使用assertIsNumeric()assertIsInt()

      【讨论】:

      • 感谢您的回答!我也将它包含在最佳答案中,因此可以立即看到。
      【解决方案6】:

      此答案适用于想知道如何确保结果是整数或整数字符串的人。 (部分cmets出现此问题):

      $this->assertEquals( 1 , preg_match( '/^[0-9]+$/', $new_id ),
          $new_id . ' is not a set of digits' );
      

      这里我们确保 preg_match 返回一个 '1',其中 preg_match 测试所有字符串字符都是数字。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-02-16
        • 2013-08-23
        • 1970-01-01
        • 2011-11-02
        • 1970-01-01
        • 1970-01-01
        • 2019-03-15
        相关资源
        最近更新 更多