dongyuan1983 2014-07-16 21:25
浏览 58
已采纳

Golang:替换功能单元测试

I'm working with Golang, and currently I'm doing some fun unit test with Testify, my file look like this

type myStruct struct {
  field_1 string

}
func (self *myStruct) writeFirst()  {
//doing something
//modify field_1
self.writeSecond()
}

func (self *myStruct) writeSecond() {
//doing something
}

In this case I'm testing writeFirst() but I'm trying to replace writeSecond() because it is using http stuff that I don't want to use because it access to internet.

I think that use a second struct and set myStruct as anonymous field will be the solution, but it's not working because me second struct and myStruct have a diferent context.

In this case I can't use mocks cause writeSecond is a method of the struct.

My test case looks like this:

func TestWriteFirst(t *testing.T) {
   myStc := myStruct{}
   assert.Equal(t,"My response", myStc.field_1)
}

All that I want is testing writeFirst without pass to writeSecond()

  • 写回答

1条回答 默认 最新

  • dtu11716 2014-07-17 06:49
    关注

    To illustrate the kind of refactoring mentioned by Not-a-Golfer in the comments, you could consider calling your second function only on an instance that is an interface:

    type F2er interface {
        Func2()
    }
    
    type S struct{ _f2 F2er }
    
    var s = &S{}
    
    func (s *S) f2() F2er {
        if s._f2 == nil {
            return s
        }
        return s._f2
    }
    
    func (s *S) Func1() {
        fmt.Println("s.Func1")
        s.f2().Func2()
    }
    

    Here: Func1 calls Func2 on s.f2(), not directly s.

    • If nothing has been set in s, s.f2() returns... itself: s
    • if s._f2 was replaced by any other struct which implements Func2, s.f2() returns that instance instead of itself.

    See a complete example in this playground script.

    Output:

    TestFunc1
    s.Func1
    s.Func2
    
    TestFunc1bis
    s.Func1
    testS.Func2    <=== different Func2 call
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Excel发现不可读取的内容
  • ¥15 UE5#if WITH_EDITOR导致打包的功能不可用
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。