XP 框架的测试

v2.1.0 2024-03-28 13:51 UTC

This package is auto-updated.

Last update: 2024-09-17 18:29:57 UTC


README

Build status on GitHub XP Framework Module BSD Licence Requires PHP 7.4+ Supports PHP 8.0+ Latest Stable Version

XP 框架的单元和集成测试

编写测试

测试位于以 "Test" 结尾的类中(测试组)并包含使用 Test 属性注解的方法(测试用例)。测试方法命名的惯例是使用小写字母,单词之间用下划线分隔,尽管这不是强制性的。

use test\{Assert, Test};

class CalculatorTest {

  #[Test]
  public function addition() {
    Assert::equals(2, (new Calculator())->add(1, 1));
  }
}

要运行这些测试,使用 test 子命令

$ xp test CalculatorTest.class.php
> [PASS] CalculatorTest
  ✓ addition

Tests cases: 1 succeeded, 0 skipped, 0 failed
Memory used: 1556.36 kB (1610.49 kB peak)
Time taken:  0.001 seconds

断言

Assert 类上存在以下简写方法

  • equals(mixed $expected, mixed $actual) - 检查两个值是否相等。内部使用 util.Objects::equal() 方法,这允许覆盖对象比较。
  • notEquals(mixed $expected, mixed $actual) - 上述方法的相反
  • true(mixed $actual) - 检查给定值是否等于布尔值 true
  • false(mixed $actual) - 检查给定值是否等于布尔值 false
  • null(mixed $actual) - 检查给定值是否为 null
  • instance(string|lang.Type $expected, mixed $actual) - 检查给定值是否是给定类型的实例。
  • matches(string $pattern, mixed $actual) - 验证给定值与给定的正则表达式匹配。
  • throws(string|lang.Type $expected, callable $actual) - 验证给定的可调用对象抛出异常。

预期失败

使用 Expect 注解,我们可以编写断言给定异常被抛出的测试

use test\{Assert, Expect, Test};

class CalculatorTest {

  #[Test, Expect(DivisionByZero::class)]
  public function division_by_zero() {
    (new Calculator())->divide(1, 0);
  }
}

要检查预期异常的消息,使用以下方法

  • 任何消息:Expect(DivisionByZero::class)
  • 精确消息:Expect(DivisionByZero::class, 'Division by zero')
  • 匹配正则表达式的消息:Expect(DivisionByZero::class, '/Division by (0|zero)/i')

值驱动测试

为了使测试代码简短并简洁,测试可能是值驱动的。值可以直接内联提供

use test\{Assert, Test, Values};

class CalculatorTest {

  #[Test, Values([[0, 0], [1, 1], [-1, 1]])]
  public function addition($a, $b) {
    Assert::equals($a + $b, (new Calculator())->add($a, $b));
  }
}

...或者如下通过引用提供者方法

use test\{Assert, Test, Values};

class CalculatorTest {

  private function operands(): iterable {
    yield [0, 0];
    yield [1, 1];
    yield [-1, 1];
  }

  #[Test, Values(from: 'operands')]
  public function addition($a, $b) {
    Assert::equals($a + $b, (new Calculator())->add($a, $b));
  }
}

先决条件

测试类和方法可能具有先决条件,测试必须成功验证才能运行

use test\verify\Runtime;
use test\{Assert, Test};

#[Runtime(extensions: ['bcmath'])]
class CalculatorTest {

  #[Test]
  public function addition() {
    Assert::equals(3, (int)bcadd(1, 2));
  }
}

以下包含验证

  • Runtime(os: '^WIN', php: '^8.0', extensions: ['bcmath']) - 运行时验证。
  • Condition(assert: 'function_exists("random_int")') - 在测试类的上下文中验证给定表达式。

传递参数给测试

特别是对于集成测试,从命令行将类似连接字符串的值传递给测试类是很重要的。将 Args 注解添加到类中,如下所示

use test\Args;
use com\mongodb\MongoConnection;

#[Args('use')]
class IntegrationTest {
  private $conn;

  public function __construct(string $dsn) {
    $this->conn= new MongoConnection($dsn);
  }

  // ...shortened for brevity
}

...然后如下传递参数

$ xp test IntegrationTest --use=mongodb://locahost
# ...

另请参阅