How to test panics?

前端 未结 7 498
别跟我提以往
别跟我提以往 2020-12-12 20:19

I\'m currently pondering how to write tests that check if a given piece of code panicked? I know that Go uses recover to catch panics, but unlike say, Java code, you can\'t

7条回答
  •  天涯浪人
    2020-12-12 20:35

    You can test which function paniced by giving panic an input

    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

提交回复
热议问题