doufei6456 2019-04-09 15:24
浏览 93
已采纳

使用PanicsWithValue进行Golang单元测试

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?

  • 写回答

1条回答 默认 最新

  • duanbai1370 2019-04-09 15:39
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?