assertArrayHasKey断言主要断言一个数组中是否存在某个key,注意了这里是说某个key,而不是某个值。当数组中存在这个key的时候则断言成功,否则断言失败。
ArrayHasKeyTest.php:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class ArrayHasKeyTest extends TestCase
{
public function testFailure(): void
{
$arr=['bar' => 'baz','bar2'=>'baz2'];
$this->assertArrayHasKey('foo', $arr);
}
}
像是这样就是断言失败:
C:\Users\Administrator>D:\phpstudy_pro\Extensions\php\php7.3.4nts\php.exe C:\Users\Administrator\PhpstormProjects\untitled\vendor\phpunit\phpunit\phpunit -c C:\Users\Administrator\PhpstormProjects\untitled\organizing\phpunit.xml C:\Users\Administrator\PhpstormProjects\untitled\organizing\tests\ArrayHasKeyTest.php
PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
F 1 / 1 (100%)
Time: 00:00.009, Memory: 6.00 MB
There was 1 failure:
1) ArrayHasKeyTest::testFailure
Failed asserting that an array has the key 'foo'.
C:\Users\Administrator\PhpstormProjects\untitled\organizing\tests\ArrayHasKeyTest.php:9
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
那么同理:ArrayHasKeyTest.php:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class ArrayHasKeyTest extends TestCase
{
public function testFailure(): void
{
$arr=['bar' => 'baz','bar2'=>'baz2'];
$this->assertArrayHasKey('bar', $arr);
}
}
这样就是断言成功:
C:\Users\Administrator>D:\phpstudy_pro\Extensions\php\php7.3.4nts\php.exe C:\Users\Administrator\PhpstormProjects\untitled\vendor\phpunit\phpunit\phpunit -c C:\Users\Administrator\PhpstormProjects\untitled\organizing\phpunit.xml C:\Users\Administrator\PhpstormProjects\untitled\organizing\tests\ArrayHasKeyTest.php
PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
. 1 / 1 (100%)
Time: 00:00.008, Memory: 6.00 MB
OK (1 test, 1 assertion)