agiledragon / gomonkey

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

打桩的方法内仅执行 return 语句,打桩没有生效 #151

Closed vector233 closed 6 months ago

vector233 commented 6 months ago

以下是测试的代码,我对 Add 方法进行了打桩,预期res直接返回0,但是实际执行结果是3,说明没有打桩成功,执行了Add的逻辑

import (
    "testing"

    "github.com/agiledragon/gomonkey/v2"
    . "github.com/smartystreets/goconvey/convey"
)

func Add(a, b int) int {
    //fmt.Println(a, b)
    return a + b
}

func Execute(a, b int) int {
    return Add(a, b)
}

func TestApplyFunc(t *testing.T) {
    Convey("TestAdd", t, func() {
        gomonkey.ApplyFunc(Add, func(a, b int) int {
            return 0
        })
        res := Execute(1, 2)
        So(res, ShouldEqual, 0)
    })
}

当我将 Add 方法增加一行fmt打印语句,打桩成功,res返回预期的 0


func Add(a, b int) int {
    fmt.Println(a, b)
    return a + b
}

请问是什么原因,能否解决呢?

agiledragon commented 6 months ago

函数太短,被内联了,可以看README或https://github.com/agiledragon/gomonkey/issues/114

vector233 commented 6 months ago

了解了。没认真看 readme,耽误大佬时间了。感谢大佬解答