agiledragon / gomonkey

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

ApplyMethod failed without pointer #88

Closed mingforpc closed 1 year ago

mingforpc commented 2 years ago

version: v2.0.2+incompatible

work on: mac x86

import (
    "fmt"
    "github.com/agiledragon/gomonkey"
    "reflect"
    "testing"
)

type A struct {
}

func (a *A) FuncA() string {
    return "FuncA"
}

func (a A) FuncB() string {
    return "FuncB"
}

func Test(t *testing.T) {
    a := &A{}
    gomonkey.ApplyMethod(reflect.TypeOf(a), "FuncA", func(_ *A) string {
        return "FuncA1"
    })

    gomonkey.ApplyMethod(reflect.TypeOf(a), "FuncB", func(_ *A) string {
        return "FuncB1"
    })

    fmt.Println(a.FuncA())
    fmt.Println(a.FuncB())
}

output:

FuncA1
FuncB

How can I mock FuncB? Thanks you!

agiledragon commented 2 years ago

func TestA(t testing.T) { a := &A{} gomonkey.ApplyMethod(reflect.TypeOf(a), "FuncA", func(_ A) string { return "FuncA1" })

b := A{}  // just b
gomonkey.ApplyMethod(reflect.TypeOf(b), "FuncB", func(_ A) string {
    return "FuncB1"
})

fmt.Println(a.FuncA())
fmt.Println(a.FuncB())

}

output:

FuncA1 FuncB1