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.

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

报告相同问题?

悬赏问题

  • ¥50 comsol稳态求解器 找不到解,奇异矩阵有1个空方程返回的解不收敛。没有返回所有参数步长;pid控制
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功