如何测试恐慌?

时间:2015-07-23 18:51:37

标签: testing go

我正在考虑如何编写测试来检查某段代码是否恐慌?我知道Go使用recover来捕捉恐慌,但与Java代码不同,你不能真正指定在恐慌或你有什么时应该跳过哪些代码。所以,如果我有一个功能:

func f(t *testing.T) {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered in f", r)
        }
    }()
    OtherFunctionThatPanics()
    t.Errorf("The code did not panic")
}

我无法确定OtherFunctionThatPanics是否恐慌,我们是否已经恢复,或者该功能是否完全没有恐慌。如果没有恐慌,如何存在恐慌,如何指定要跳过哪些代码?我怎样才能检查是否有一些恐慌从中恢复过来?

8 个答案:

答案 0 :(得分:70)

testing并没有“成功”的概念,只有失败。所以你上面的代码是正确的。您可能会发现这种风格稍微清晰一些,但基本上是相同的。

func TestPanic(t *testing.T) {
    defer func() {
        if r := recover(); r == nil {
            t.Errorf("The code did not panic")
        }
    }()

    // The following is the code under test
    OtherFunctionThatPanics()
}

我通常认为testing相当弱。您可能对更强大的测试引擎感兴趣,例如Ginkgo。即使您不想要完整的Ginkgo系统,也可以只使用其匹配库Gomega,它可以与testing一起使用。 Gomega包括以下匹配器:

Expect(OtherFunctionThatPanics).To(Panic())

您还可以将恐慌检查结合到一个简单的函数中:

func TestPanic(t *testing.T) {
    assertPanic(t, OtherFunctionThatPanics)
}

func assertPanic(t *testing.T, f func()) {
    defer func() {
        if r := recover(); r == nil {
            t.Errorf("The code did not panic")
        }
    }()
    f()
}

答案 1 :(得分:18)

如果你使用testify/assert,那么它就是一个单行:

func TestOtherFunctionThatPanics(t *testing.T) {
  assert.Panics(t, OtherFunctionThatPanics, "The code did not panic")
}

或者,如果您的OtherFunctionThatPanics的签名不是func()

func TestOtherFunctionThatPanics(t *testing.T) {
  assert.Panics(t, func() { OtherFunctionThatPanics(arg) }, "The code did not panic")
}

如果您尚未尝试作证,请查看testify/mock。超级简单的断言和嘲笑。

答案 2 :(得分:5)

简洁方式

对我来说,以下解决方案易于阅读,并向维护人员展示了受测试的自然代码流。

func TestPanic(t *testing.T) {
    // No need to check whether `recover()` is nil. Just turn off the panic.
    defer func() { recover() }()

    OtherFunctionThatPanics()

    // Never reaches here if `OtherFunctionThatPanics` panics.
    t.Errorf("did not panic")
}

对于更通用的解决方案,您也可以这样做:

func TestPanic(t *testing.T) {
    shouldPanic(t, OtherFunctionThatPanics)
}

func shouldPanic(t *testing.T, f func()) {
    defer func() { recover() }()
    f()
    t.Errorf("should have panicked")
}

答案 3 :(得分:3)

您可以这样做:

func f(t *testing.T) {
    recovered := func() (r bool) {
        defer func() {
            if r := recover(); r != nil {
                r = true
            }
        }()
        OtherFunctionThatPanics()
        // NOT BE EXECUTED IF PANICS
        // ....
    }
    if ! recovered() {
        t.Errorf("The code did not panic")

        // EXECUTED IF PANICS
        // ....
    }
}

作为通用的应急路由器功能,这也将起作用:

https://github.com/7d4b9/recover

package recover

func Recovered(IfPanic, Else func(), Then func(recover interface{})) (recoverElse interface{}) {
    defer func() {
        if r := recover(); r != nil {
            {
                // EXECUTED IF PANICS
                if Then != nil {
                    Then(r)
                }
            }
        }
    }()

    IfPanic()

    {
        // NOT BE EXECUTED IF PANICS
        if Else != nil {
            defer func() {
                recoverElse = recover()
            }()
            Else()
        }
    }
    return
}

var testError = errors.New("expected error")

func TestRecover(t *testing.T) {
    Recovered(
        func() {
            panic(testError)
        },
        func() {
            t.Errorf("The code did not panic")
        },
        func(r interface{}) {
            if err := r.(error); err != nil {
                assert.Error(t, testError, err)
                return
            }
            t.Errorf("The code did an unexpected panic")
        },
    )
}

答案 4 :(得分:2)

当您需要检查恐慌的内容时,可以对恢复的值进行类型转换:

func TestIsAheadComparedToPanicsWithDifferingStreams(t *testing.T) {
    defer func() {
        err := recover().(error)

        if err.Error() != "Cursor: cannot compare cursors from different streams" {
            t.Fatalf("Wrong panic message: %s", err.Error())
        }
    }()

    c1 := CursorFromserializedMust("/foo:0:0")
    c2 := CursorFromserializedMust("/bar:0:0")

    // must panic
    c1.IsAheadComparedTo(c2)
}

如果您正在测试的代码没有出现紧急情况或因为出现错误而出现错误或恐慌,那么测试将失败(这是您想要的)。

答案 5 :(得分:2)

当循环遍历多个测试用例时,我会选择以下内容:

package main

import (
    "reflect"
    "testing"
)


func TestYourFunc(t *testing.T) {
    type args struct {
        arg1 int
        arg2 int
        arg3 int
    }
    tests := []struct {
        name      string
        args      args
        want      []int
        wantErr   bool
        wantPanic bool
    }{
        //TODO: write test cases
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            defer func() {
                r := recover()
                if (r != nil) != tt.wantPanic {
                    t.Errorf("SequenceInt() recover = %v, wantPanic = %v", r, tt.wantPanic)
                }
            }()
            got, err := YourFunc(tt.args.arg1, tt.args.arg2, tt.args.arg3)
            if (err != nil) != tt.wantErr {
                t.Errorf("YourFunc() error = %v, wantErr %v", err, tt.wantErr)
                return
            }
            if !reflect.DeepEqual(got, tt.want) {
                t.Errorf("YourFunc() = %v, want %v", got, tt.want)
            }
        })
    }
}

Go playground

答案 6 :(得分:2)

以下是我预期的恐慌

func TestPanic(t *testing.T) {

    panicF := func() {
        //panic call here
    }
    require.Panics(t, panicF)
}

答案 7 :(得分:0)

您可以通过提供恐慌输入来测试哪个功能处于恐慌状态

package main

import "fmt"

func explode() {
    // Cause a panic.
    panic("WRONG")
}

func explode1() {
    // Cause a panic.
    panic("WRONG1")
}

func main() {
    // Handle errors in defer func with recover.
    defer func() {
        if r := recover(); r != nil {
            var ok bool
            err, ok := r.(error)
            if !ok {
                err = fmt.Errorf("pkg: %v", r)
                fmt.Println(err)
            }
        }

    }()
    // These causes an error. change between these
    explode()
    //explode1()

    fmt.Println("Everything fine")

}

http://play.golang.org/p/ORWBqmPSVA