How to test os.exit scenarios in Go

后端 未结 5 1840
渐次进展
渐次进展 2020-12-23 12:09

Given this code

func doomed() {
  os.Exit(1)
}

How do I properly test that calling this function will result in an exit using go test

5条回答
  •  旧巷少年郎
    2020-12-23 12:15

    I do this by using bouk/monkey:

    func TestDoomed(t *testing.T) {
      fakeExit := func(int) {
        panic("os.Exit called")      
      }
      patch := monkey.Patch(os.Exit, fakeExit)
      defer patch.Unpatch()
      assert.PanicsWithValue(t, "os.Exit called", doomed, "os.Exit was not called")
    }
    

    monkey is super-powerful when it comes to this sort of work, and for fault injection and other difficult tasks. It does come with some caveats.

提交回复
热议问题