當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


PHP PHPUnit assertCount()用法及代碼示例


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()。



相關用法


注:本文由純淨天空篩選整理自Shivam.Pradhan大神的英文原創作品 PHPunit | assertCount() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。