k2gl / phpunit-fluent-assertions
提高测试代码的可读性。
11.0.2
2024-04-21 15:37 UTC
Requires
- php: >=8.1
- phpunit/phpunit: ^9|^10|^11
README
这个库受到了Vladimir Khorikov的启发,他是《单元测试:原则、模式和实践》一书的作者,它使得测试中的检查更加易于阅读。
安装
您可以使用Composer将此库作为本地、按项目依赖项添加到您的项目中。
composer require --dev k2gl/phpunit-fluent-assertions
使用方法
像往常一样编写测试,只需使用流畅断言的简写别名 check($x)->...;
,expect($x)->...;
或 fact($x)->...;
,而不是使用 self::assert...($x, $y)
。
// arrange $user = UserFactory::createOne([ 'phone' => $phoneBefore = faker()->e164PhoneNumber; ]); // act $user->setPhone( $phoneAfter = faker()->e164PhoneNumber ); // assert // traditional PHPUnit assertions self::assertSame(expected: $phoneAfter, actual: $user->getPhone()); self::assertNotSame(expected: $phoneBefore, actual: $user->getPhone()); // fluent assertions fact($user->getPhone()) ->is($phoneAfter) ->equals($phoneAfter) ->not($phoneBefore) ->true() ->notTrue() ->false() ->notFalse() ->null() ->notNull() ->matchesRegularExpression('#^\d+$#') ->notMatchesRegularExpression('#^\D+$#') ->containsString('alpha') ->notContainsString('alpha') ->containsStringIgnoringCase('beta') ->notContainsStringIgnoringCase('beta') ->count(5) ->notCount(5) ->arrayHasKey('echo') ->arrayNotHasKey('echo') ->instanceOf(UserFactory::class) ->notInstanceOf(UserFactory::class) ->ulid() // Universally Unique Lexicographically Sortable Identifier https://github.com/ulid/spec ... ; fact( [ 'a' => ['any' => 'thing'], 'b' => ['any' => 'thing', 'type' => 'candy', 'color' => 'green'], 'c' => ['miss' => 'kiss', 'foo' => 'bar', 'any' => 'thing'], 'd' => ['any' => 'thing'], ] )->arrayContainsAssociativeArray( [ 'c' => ['foo' => 'bar', 'miss' => 'kiss'], 'b' => ['color' => 'green'], ] ); // true