如何测试doStuff功能?(游乐场:http : //play.golang.org/p/aPFSlaBLgX)package myPackagevar locked = falsefunc 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}换句话说:如何测试使用defer语句的代码?应该使用哪些一般策略来测试延迟调用?如果没有通用的做法,如何测试这个具体的代码?PS:去游乐场只允许 package main
1 回答
慕雪6442864
TA贡献1812条经验 获得超5个赞
为了测试恐慌状态,应该推迟断言
看起来要测试一个panic状态,我们应该defer测试断言:
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
}
发生这种情况是doStuff()因为我们正在模拟 a panic,因此下面没有执行任何代码,因此应该推迟断言,以便它们处于“恐慌范围”。
- 1 回答
- 0 关注
- 205 浏览
添加回答
举报
0/150
提交
取消