How to test panics?

前端 未结 7 517
别跟我提以往
别跟我提以往 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:32

    When you need to check the content of the panic, you can typecast the recovered value:

    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)
    }
    

    If the code you're testing does not panic OR panic with an error OR panic with the error message you expect it to, the test will fail (which is what you'd want).

提交回复
热议问题