Search code examples
unit-testinggotestify

Golang unit testing using PanicsWithValue


We are trying to test a function that raises an index out of range error.

The code of the unit test is simple, something like:

import (
    "testing"

    "github.com/stretchr/testify/assert"
)

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

But unfortunately the test Fails with a strange error

=== 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

You can see that the panic value and the error show the same, but test still fails.
Any ideas what is going on?


Solution

  • The index out of range error has type runtime.errorString. The application compares the value to a value of type string. This comparison evaluates to false.

    To fix, capture the index out of range error and compare to that.

    var indexOutOfRangeValue = func() (v interface{}) {
        defer func() {
            v = recover()
        }()
        x := []int{}
        return x[1]
    }()
    
    func TestIndexOutOfRange(t *testing.T) {
        assert.PanicsWithValue(t, indexOutOfRangeValue, func() { indexOutOfRange(9) })
    }
    

    This code assumes that index out of range panic values compare as equal. There's no guarantee that this assumption will be true in future versions of Go, but it seems unlikely that the runtime break this assumption.