agiledragon / gomonkey

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

ApplyMethod failed to replace #170

Open 123jixinyu opened 1 week ago

123jixinyu commented 1 week ago
package main

import (
    "fmt"
    "github.com/agiledragon/gomonkey/v2"
    . "github.com/smartystreets/goconvey/convey"
    "reflect"
    "testing"
)

type A struct {
    B *B
}

func (a *A) TestA() {
    fmt.Println(a.B.TestB())
    fmt.Println(2)
}

type B struct {
}

func (*B) TestB() int {
    return 1
}

func TestSpec(t *testing.T) {

    Convey("Test Spec", t, func() {

        b := &B{}
        patches := gomonkey.ApplyMethod(reflect.TypeOf(b), "TestB", func(_ *B) int {
            return 3
        })
        defer patches.Reset()

        a := A{B: b}
        a.TestA()
    })
}

output

1
2

but it should be 3 2 , why not works???

LinxiItIs commented 1 week ago

try '-gcflags=all=-N -l' to close inline

123jixinyu commented 1 week ago

i tried it. it`s working now

123jixinyu commented 1 week ago

try '-gcflags=all=-N -l' to close inline

extremely grateful