0

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?

Helder Sepulveda
  • 15,500
  • 4
  • 29
  • 56
  • 1
    Edit the question to give the import path of the `assert` package and the code for `indexOutOfRange`. – Charlie Tumahai Apr 09 '19 at 15:27
  • @CeriseLimón Added the import of `assert` it is part of the `github.com/stretchr/testify/assert` – Helder Sepulveda Apr 09 '19 at 15:35
  • Does the function really panic? Do you call `panic()` inside that function? You should not test an internal panic, because if the language changes, your tests will fail without changing anything in your code. – apxp Apr 09 '19 at 15:39

1 Answers1

4

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.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242