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

使用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.

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

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改