首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过反射测试Go中的函数集合?

如何通过反射测试Go中的函数集合?
EN

Stack Overflow用户
提问于 2013-12-29 09:40:38
回答 1查看 2K关注 0票数 13

我必须为几个具有相似签名和返回值(对象和错误)的函数编写单元测试,这些函数必须通过类似的测试条件。

我想避免写:

代码语言:javascript
复制
func TestFunc1(t *testing.T) {
    // tests on return values
}
func TestFunc2(t *testing.T) {
    // tests identical for Func1
}
func TestFunc3(t *testing.T) {
    // tests identical for Func1
}
...

(更完整的上下文请参见这个去操场的例子 )

(是的,go游乐场还不支持go test,只有go run第6511期需要这个功能)

如何使用反射(套餐),以便只编写一个测试:

  • 依次调用每个函数?
  • 测试它们的返回值?

我见过:

但是,我忽略了调用函数和在测试中使用返回值的完整示例。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-12-29 09:40:38

一旦我理解了一切都必须使用或返回类型值,下面是我想出的。

诀窍是使用:

  • ValueOf,以便获得接收方的值。
  • Value.MethodByName用于查找接收方值的函数
  • Value.IsNil测试nil返回的值。

测试代码的主要摘录:

代码语言:javascript
复制
var funcNames = []string{"Func1", "Func2", "Func3"}

func TestFunc(t *testing.T) {
    stype := reflect.ValueOf(s)
    for _, fname := range funcNames {

        fmt.Println(fname)

        sfunc := stype.MethodByName(fname)
        // no parameter => empty slice of Value
        ret := sfunc.Call([]reflect.Value{})

        val := ret[0].Int()

        // That would panic for a nil returned err
        // err := ret[1].Interface().(error)
                err := ret[1]

        if val < 1 {
            t.Error(fname + " should return positive value")
        }
        if err.IsNil() == false {
            t.Error(fname + " shouldn't err")
        }

    }
}

看一个围棋操场中的可运行示例

请注意,如果您使用不存在的函数名调用该测试函数,则会引起恐慌。

这里的例子

代码语言:javascript
复制
runtime.panic(0x126660, 0x10533140)
    /tmp/sandbox/go/src/pkg/runtime/panic.c:266 +0xe0
testing.func·005()
    /tmp/sandbox/go/src/pkg/testing/testing.go:383 +0x180
----- stack segment boundary -----
runtime.panic(0x126660, 0x10533140)
    /tmp/sandbox/go/src/pkg/runtime/panic.c:248 +0x160
reflect.flag.mustBe(0x0, 0x13)
    /tmp/sandbox/go/src/pkg/reflect/value.go:249 +0xc0
reflect.Value.Call(0x0, 0x0, 0x0, 0xfeef9f28, 0x0, ...)
    /tmp/sandbox/go/src/pkg/reflect/value.go:351 +0x40
main.TestFunc(0x10546120, 0xe)
    /tmpfs/gosandbox-3642d986_9569fcc1_f443bbfb_73e4528d_c874f1af/prog.go:34 +0x240

去操场,从恐慌中恢复过来,但是你的测试程序可能不会。

这就是为什么我在上面添加了测试函数:

代码语言:javascript
复制
for _, fname := range funcNames {

    defer func() {
        if x := recover(); x != nil {
            t.Error("TestFunc paniced for", fname, ": ", x)
        }
    }()
    fmt.Println(fname)

这会产生(见示例)更好的输出:

代码语言:javascript
复制
Func1
Func2
Func3
Func4
--- FAIL: TestFunc (0.00 seconds)
    prog.go:48: Func2 should return positive value
    prog.go:51: Func3 shouldn't err
    prog.go:32: TestFunc paniced for Func4 :  reflect: call of reflect.Value.Call on zero Value
FAIL
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20823836

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档