You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让PHPUnit中assertEquals断言失败时显示完整差异?

解决PHPUnit测试失败时输出截断长字符串的问题

当PHPUnit对比数组或长字符串失败时,默认会截断过长内容,导致无法查看关键信息。可以通过以下两种方式取消截断:

临时生效:使用命令行参数

执行测试时添加--no-truncate参数,即可让输出显示完整内容:

phpunit --no-truncate UnitTest.php

执行后,测试失败的输出会完整展示长字符串:

There was 1 failure:

1) UnitTest::testAssertingArrays
Expected empty array but got non-empty array.
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
 Array (
-    0 => 'Some short string'
-    1 => 'Some really long string that just keeps going and going and going but contains important clue HERE about why this whole test failed.'
 )

永久生效:修改PHPUnit配置文件

在项目的phpunit.xml或phpunit.xml.dist配置文件中,给根节点<phpunit>添加truncateStrings="false"属性,后续所有测试都会默认显示完整内容:

<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.5/phpunit.xsd"
         truncateStrings="false">
    <!-- 其他原有配置 -->
</phpunit>

补充说明

若使用PHPUnit 8之前的版本,--no-truncate参数可能不支持,此时可优先考虑升级PHPUnit版本,也可通过自定义输出打印机实现完整输出,但后者操作复杂度较高。

内容的提问来源于stack exchange,提问作者Mikko Rantalainen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 01:10:11