5.11.15

Test your panics in golang

Panicing in golang is a way of exiting a program in a way where you have some degree of control over what is happening, in some ways, its similar to a RuntimeException in java.

However, in unit tests these sorts of functions are notoriously hard to deal with, since they have side effects.  In golang, we can use a defer to capture and assert a panic, like so:

 defer func() {
        // recover from panic if one occured. Set err to nil otherwise.
        err = recover()
    }()
How does defer work?  It puts function calls on a stack, and they are popped one after another at
the end of a function.  So for example,

defer func() { doA() }
defer func() { doB() }

After these calls occur, we have B sitting on top of A in a stack.  So, make sure to order your defers in reverse order from how they are called!

In this case, Int(0) panics.  We have two defer functions.  The final one is the one at the top.

There might be better ways to test panics in golang.  This is just the hack I'm using for now :)


Oh by the way... a simple optimization?  Don't do two defers. You can do it all in one, because recover() returns nil if there is no error.  BUT, if I told you that in the beginning, you wouldn't know how defer() really worked now would you !

No comments:

Post a Comment