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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常