使用PanicsWithValue测试索引越界Panic失败问题求助
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

