assertCount()函数是PHPUnit中的内置函数,用于断言一个数组,以包含与给定计数值相同数量的元素。如果数组仅包含确切数量的元素,则此断言将返回true,因为给定count则返回false。如果为真,则通过断言的测试用例,否则测试用例失败。
用法:
assertCount( integer $expectedCount, array $array, string $message = '' )
参数:该函数接受三个参数,如上面的语法所示。参数说明如下:
- $expectedCount:此参数是整数,是数组的预期元素数。
- $array:此参数是一个数组,assert函数将为其检查是否包含与给定计数值相同数量的元素。
- $message:此参数采用字符串值。当测试用例失败时,此字符串消息将显示为错误消息。
以下程序说明了PHPUnit中的assertCount()函数:
程序1:
<?php
use PHPUnit\Framework\TestCase;
class GeeksPhpunitTestCase extends TestCase
{
public function testNegativeTestcaseForAssertCount()
{
$testArray = array(1, 2, 3, 4);
// Assert function to test whether testArray contains
// same number of elements as expectedCount
$expectedCount = 3;
$this->assertCount(
$expectedCount,
$testArray, "testArray doesn't contains 3 elements"
);
}
}
?>
输出:
PHPUnit 8.2.5 by Sebastian Bergmann and contributors. F 1 / 1 (100%) Time:66 ms, Memory:10.00 MB There was 1 failure: 1) GeeksPhpunitTestCase::testNegativeTestcaseForAssertCount testArray doesn't contains 3 elements Failed asserting that actual size 4 matches expected size 3. /home/shivam/Documents/geeks/phpunit/abc.php:14 FAILURES! Tests:1, Assertions:1, Failures:1.
程序2:
<?php
use PHPUnit\Framework\TestCase;
class GeeksPhpunitTestCase extends TestCase
{
public function testPositiveTestcaseForAssertCount()
{
$testArray = array(1, 2, 3, 4);
// Assert function to test whether testArray contains
// same number of elements as expectedCount
$expectedCount = 4;
$this->assertCount(
$expectedCount,
$testArray, "testArray contains 3 elements"
);
}
}
?>
输出:
PHPUnit 8.2.5 by Sebastian Bergmann and contributors. . 1 / 1 (100%) Time:67 ms, Memory:10.00 MB OK (1 test, 1 assertion)
注意:要使用phpunit运行测试用例,请遵循此处的步骤。另外,phpunit 7及更高版本支持assertCount()。
相关用法
- PHP PHPUnit assertStringContainsStringIgnoringCase()用法及代码示例
- PHP PHPUnit assertEmpty()用法及代码示例
- PHP PHPUnit assertNotContains()用法及代码示例
- PHP PHPUnit assertEquals()用法及代码示例
- PHP PHPUnit assertDirectoryNotIsWritable()用法及代码示例
- PHP PHPUnit assertStringContainsString()用法及代码示例
- PHP PHPUnit assertContainsOnlyInstancesOf()用法及代码示例
- PHP PHPUnit assertStringNotContainsStringIgnoringCase()用法及代码示例
- PHP PHPUnit assertClassHasAttribute()用法及代码示例
- PHP PHPUnit assertArrayNotHasKey()用法及代码示例
- PHP PHPUnit assertArraySubset()用法及代码示例
- PHP PHPUnit assertArrayHasKey()用法及代码示例
- PHP PHPUnit assertDirectoryIsReadable()用法及代码示例
- PHP PHPUnit assertNotEquals()用法及代码示例
- PHP PHPUnit assertClassHasStaticAttribute()用法及代码示例
注:本文由纯净天空筛选整理自Shivam.Pradhan大神的英文原创作品 PHPunit | assertCount() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。