當(dāng)有測試失敗時,PHPUnit 全力提供盡可能多的有助于找出問題所在的上下文信息。
示例 2.15 數(shù)組比較失敗時生成的錯誤輸出
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class ArrayDiffTest extends TestCase
{
public function testEquality(): void
{
$this->assertSame(
[1, 2, 3, 4, 5, 6],
[1, 2, 33, 4, 5, 6]
);
}
}
$ phpunit ArrayDiffTest
PHPUnit latest.0 by Sebastian Bergmann and contributors.
F
Time: 0 seconds, Memory: 5.25Mb
There was 1 failure:
1) ArrayDiffTest::testEquality
Failed asserting that two arrays are identical.
--- Expected
+++ Actual
@@ @@
Array (
0 => 1
1 => 2
- 2 => 3
+ 2 => 33
3 => 4
4 => 5
5 => 6
)
/home/sb/ArrayDiffTest.php:7
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
在這個例子中,數(shù)組中只有一個值不同,但其他值也都同時顯示出來,以提供關(guān)于錯誤發(fā)生的位置的上下文信息。
當(dāng)生成的輸出很長而難以閱讀時,PHPUnit 將對其進(jìn)行分割,并在每個差異附近提供少數(shù)幾行上下文信息。
示例 2.16 長數(shù)組的數(shù)組比較失敗時的錯誤輸出
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class LongArrayDiffTest extends TestCase
{
public function testEquality(): void
{
$this->assertSame(
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 33, 4, 5, 6]
);
}
}
$ phpunit LongArrayDiffTest
PHPUnit latest.0 by Sebastian Bergmann and contributors.
F
Time: 0 seconds, Memory: 5.25Mb
There was 1 failure:
1) LongArrayDiffTest::testEquality
Failed asserting that two arrays are identical.
--- Expected
+++ Actual
@@ @@
11 => 0
12 => 1
13 => 2
- 14 => 3
+ 14 => 33
15 => 4
16 => 5
17 => 6
)
/home/sb/LongArrayDiffTest.php:7
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
當(dāng)比較失敗時,PHPUnit 為輸入值建立文本表示,然后以此進(jìn)行對比。這種實(shí)現(xiàn)導(dǎo)致在差異指示中顯示出來的問題可能比實(shí)際上存在的多。
這種情況只出現(xiàn)在對數(shù)組或者對象使用 ?assertEquals()
? 或其他“弱”比較函數(shù)時。
示例 2.17 使用弱比較時在差異生成過程中的邊緣情況
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class ArrayWeakComparisonTest extends TestCase
{
public function testEquality(): void
{
$this->assertEquals(
[1, 2, 3, 4, 5, 6],
['1', 2, 33, 4, 5, 6]
);
}
}
$ phpunit ArrayWeakComparisonTest
PHPUnit latest.0 by Sebastian Bergmann and contributors.
F
Time: 0 seconds, Memory: 5.25Mb
There was 1 failure:
1) ArrayWeakComparisonTest::testEquality
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
Array (
- 0 => 1
+ 0 => '1'
1 => 2
- 2 => 3
+ 2 => 33
3 => 4
4 => 5
5 => 6
)
/home/sb/ArrayWeakComparisonTest.php:7
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
在這個例子中,第一個索引項(xiàng)中的 1 和 '1' 在報告中被視為不同,雖然 ?assertEquals()
? 認(rèn)為這兩個值是匹配的。
更多建議: