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

使用PanicsWithValue测试索引越界Panic失败问题求助

Why does assert.PanicsWithValue fail even when the panic message matches exactly?

The Problem

I wrote a unit test to catch an "index out of range" panic using testify's assert.PanicsWithValue, but the test fails even though the expected and actual panic messages are identical:

Test code:

import (
    "testing"
    "github.com/stretchr/testify/assert"
)

func TestIndexOutOfRange(t *testing.T) {
    assert.PanicsWithValue(t, "index out of range", func() {
        indexOutOfRange(9)
    })
}

Error output:

=== RUN   TestIndexOutOfRange
--- FAIL: TestIndexOutOfRange (0.00s)
<autogenerated>:1: Error Trace: badindex_test.go:55
Error:      func (assert.PanicTestFunc)(0x1c440d0) should panic with value: "index out of range"
Panic value: "index out of range"
Test:       TestIndexOutOfRange

The Root Cause

The issue boils down to a type mismatch. When Go's runtime throws an "index out of range" panic, the value being panicked isn't a raw string — it's an instance of an internal runtime.errorString type (which implements the error interface), not the string literal you're passing to PanicsWithValue.

assert.PanicsWithValue does a strict equality check: both the value and its underlying type must match exactly. Even though the string representation looks identical, the types don't align, so the assertion fails.

The Fix

Use assert.PanicsWithError instead — this method is purpose-built to match the error message string regardless of the underlying error type:

func TestIndexOutOfRange(t *testing.T) {
    assert.PanicsWithError(t, "index out of range", func() {
        indexOutOfRange(9)
    })
}

If you absolutely had to use PanicsWithValue, you'd need to match the exact runtime error type, but that's not recommended since it relies on Go's internal implementation details. PanicsWithError is the safe, intended way to test for panic messages from runtime errors.

内容的提问来源于stack exchange,提问作者Helder Sepulveda

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:48:42