star/结构断言

使用流畅接口断言数组结构的PHP工具

0.1 2020-07-08 14:27 UTC

This package is auto-updated.

Last update: 2024-09-17 15:13:10 UTC


README

使用流畅接口断言数组结构的PHP工具。

Build Status

安装

使用 Composer,运行 composer require --dev star/structure-assertion

用法

当您有 PHPUnit 测试,并且想要断言数组的一些节点时,这个库非常有用。

StructureAssertion::fromArray(
    [
        'data' => [
            'id' => 11,
            'array' => [
                1, 
                2,
                3,
            ],
        ],
    ]
)
    ->enterObjectNode('data') // Assert the node 'data' exists and is an object
    ->assertIsSame('id', 11) // Assert the object's property 'id' exists and match the exact value
    ->enterArrayNode('array') // Assert the node 'data' exists and is an array
    ->assertCount(3); // Assert the number of item is exactly 3

构造方法

  • StructureAssertion::fromArray($array);:使用给定的数组。
  • StructureAssertion::fromJsonResponse($response);:使用假设具有JSON内容的Response对象构建。

断言方法

按照惯例,所有断言方法均以 assert* 命名。在底层,StructureAssertion 使用PHPUnit断言。许多断言以PHPUnit的约束命名。

如果未定义特定断言,可以使用 StructureAssertion::assertCallback() 方法使用自己的断言。

例如。

StructureAssertion::fromArray($data)
    ->assertCallback('property', function ($value): bool {
        // When it evaluates to false, the expectation will fail
        // return true | false
    });

导航方法

要导航节点,可以使用以 enter* 开头的方法。我们假设当前节点位于正确的位置。

  • StructureAssertion::exitNode():将内部指针移动到父节点。
  • StructureAssertion::nextArrayElement():是 exitNode()->enterArrayElement($current + 1) 的快捷方式。进入索引 + 1 的下一个元素。仅适用于整数索引元素。

调试方法

该库还提供调试方法,以便了解光标的位置。

  • StructureAssertion::dump($maxDepth = 2, $dumpStrategy):将使用 $strategy 和最多 $maxDepth 的当前节点进行转储。
  • StructureAssertion::dumpPath($dumpStrategy):将使用 $strategy 将当前节点路径进行转储。
  • StructureAssertion::dumpKeys($dumpStrategy):将使用 $strategy 将当前节点键进行转储。

贡献

欢迎任何贡献,只需提出一个Pull请求,我们将考虑它。