gong023/assert_chain

使您可以使用方法链使用phpunit assert

0.2.0 2017-10-13 16:51 UTC

This package is auto-updated.

Last update: 2024-08-27 19:47:25 UTC


README

Build Status

AssertChain是PHPUnit助手。它使您能够使用方法链编写PHPUnit assert。

设置

使用composer安装AssertChain。

composer require --dev gong023/assert_chain:dev-master
# install phpunit if you do not install yet.
# composer require --dev phpunit/phpunit:4.*

将AssertChain trait导入您的测试类。

class YourTestClass extends \PHPUnit_Framework_TestCase
{
    use AssertChain\AssertChain;
}

用法

首先调用assert,然后根据需要持续断言。

您可以使用PHPUnit_Framework_Assert中的所有断言。

public function testWithArray()
{
    $arr = [
        'intKey'    => 1,
        'stringKey' => 'foo',
        'boolKey'   => true,
    ];

    $this->assert()
      ->notEmpty($arr)
      ->arrayHasKey('intKey', $arr)
      ->same(1, $arr['intKey'])
      ->arrayHasKey('stringKey', $arr)
      ->same('foo', $arr['stringKey'])
      ->arrayHasKey('boolKey', $arr)
      ->true($arr['boolKey']);

    /*
     * above code is equal to this.
     *
     * $this->assertNotEmpty($arr);
     * $this->assertArrayHasKey('intKey', $arr);
     * $this->assertSame(1, $arr['intKey']);
     * $this->assertArrayHasKey('stringKey', $arr);
     * $this->assertSame('foo', $arr['stringKey']);
     * $this->assertArrayHasKey('boolKey', $arr);
     * $this->assertTrue($arr['boolKey']);
     */
}

如果您厌倦了多次编写$actual值,可以使用centralizedAssert

public function testWithArray()
{
    $arr = ['key' => 'value'];

    $this->centralizedAssert($arr)
      ->notNull()
      ->notEmpty()
      ->notCount(0)
      ->count(1)
      ->arrayNotHasKey('no existing key')
      ->arrayHasKey('key')
      ->notContains('no existing value')
      ->contains('value')
      ->equals(['key' => 'value']);

    /*
     * above code is equal to this.
     *
     * $this->assertNotNull($arr);
     * $this->assertNotEmpty($arr);
     * $this->assertNotCount(0, $arr);
     * $this->assertCount(1, $arr);
     * $this->assertArrayNotHasKey('no existing key', $arr);
     * $this->assertNotContains('no existing value', $arr);
     * $this->assertContains('value', $arr);
     * $this->assertEquals(['key' => 'value']);
     */
}

centralizedAssert自动将$actual值设置到PHPUnit_Framework_Assert中的每个断言。

您不需要多次输入$actual值。

如果您想了解有关centralizedAssert的更多信息,请参阅AssertChain测试类

IDE友好

AssertChain是IDE友好的。您可以获得方法自动完成。