记录 gomonkey 指针报错

报错日志

可以看到报错信息中出现unexpected fault address,说明是指针出了问题。

unexpected fault address 0x4000185960
fatal error: fault
[signal SIGSEGV: segmentation violation code=0x2 addr=0x4000185960 pc=0x4000185960]

goroutine 6 [running]:
......

goroutine 1 [chan receive]:
......

goroutine 19 [chan receive]:
......

定位问题

原代码:我多次调用了gomockey.ApplyMethod()

func (s *Suite) TestFunc() {
  type TestCase struct {
    ......
  }
  
  for _, tc := range testCases {
    gomonkey.ApplyMethod() {
      ......
    })
    
    gomonkey.ApplyMethod() {
      ......
    })
    
    gomonkey.ApplyMethod() {
      ......
    })
    
    err := s.svc.TestFunc()
    assert.Equal(s.T(), err, nil, "Test failed")
  }
}

猜测可能是多次调用gomockey.ApplyMethod()导致创建了多个gomonkey.Patches对象

解决方案

创建一个gomonkey.Patches对象,用此对象重复调用 ApplyMethod()

func (s *Suite) TestFunc() {
  type TestCase struct {
    ......
  }
  
  
  var patches *gomonkey.Patches
  for _, tc := range testCases {
    patches = gomonkey.ApplyMethod() {
      ......
    })
    
    patches.ApplyMethod() {
      ......
    })
    
    patches.ApplyMethod() {
      ......
    })
    
    err := s.svc.TestFunc()
    assert.Equal(s.T(), err, nil, "Test failed")
    patches.Reset()
  }
}