douyannuo7733 2014-12-24 02:29
浏览 14
已采纳

如何测试延迟的Go语句?

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

  • 写回答

1条回答 默认 最新

  • douren1928 2014-12-24 05:06
    关注

    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".

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 关于无人驾驶的航向角
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了