How can I test doStuff
function? (Playground: http://play.golang.org/p/aPFSlaBLgX)
package myPackage
var locked = false
func doStuff() {
defer unlock()
lock()
// some task that can cause errors
// need to test if lock was really unlocked
// this is just a simple example, things can go complex on real world
panic("!")
}
func lock() {
locked = true
}
func unlock() {
locked = false
}
In other words: how to test code that uses defer
statements? What general strategies should be used to test deferred calls? If there are no general practice, how to test this specific code?
PS: Go playground only allows package main
TL;DR
To test a panicked state the assertions should be deffered
Looks like that to test a panic
state we should defer
the test assertions:
package myPackage
import "testing"
func TestLock(t *testing.T) {
defer func (){
if locked == true {
t.Error("Expected locked to be false but got locked =", locked)
}
}() // do assertions on panicked state ↑
defer func (){ recover() }() // recover from panic ↑
doStuff() // this will panic and code execution will flow up ↑
// and, of course, execution will never reach below this line ---
// don't put assertions here
}
This happens because no code is executed below doStuff()
since we are simulating a panic
, therefore the assertions should be deferred so they will be on "panicked scope".