agiledragon / gomonkey

gomonkey is a library to make monkey patching in unit tests easy
MIT License
2k stars 179 forks source link

goroutine 进行mock的方案求解 #47

Closed ycxb0315 closed 3 years ago

ycxb0315 commented 3 years ago

在开发的业务场景中,有时候会遇到中间有一个函数中有一个协程,类似下面这种

func testGoroutine() {
    go PrintNum()
    time.Sleep(time.Second * 1)
}

// PrintNum printnum
func PrintNum() {
    for i := 0; i < 5; i++ {
        fmt.Print(i)
    }
}

如果使用gomonkey对PrintNum进行mock,代码如下:

func Test_testGoroutine(t *testing.T) {
    Convey("test function", t, func() {
        patches1 := ApplyFunc(PrintNum, func() {
            fmt.Print("mock")
        })

        defer patches1.Reset()
        testGoroutine()
    })
}

但因为主线程可能提前Reset的缘故,PrintNum函数可能没有Mock成功,但是不Reset,在全包进行测试的时候,会不会影响其他函数测试, 虽然我也看到gomonkey不能用于并发,但还是想请问这种情况有什么好的解决方案吗?多谢啦

Delete-S commented 8 months ago

@ycxb0315 这个问题解决了么?