agiledragon / gomonkey

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

私有函数有办法进行mock吗? #98

Closed yourenawo closed 2 years ago

yourenawo commented 2 years ago

我现在在补以前写的代码,有些函数是私有的,需要mock掉。

JiaLiangoooo commented 2 years ago
Convey("TestApplyPrivateMethod", t, func() {
        Convey("patch private pointer method in the different package", func() {
            f := new(fake.PrivateMethodStruct)
            var s *fake.PrivateMethodStruct
            patches := ApplyPrivateMethod(s, "ok", func(_ *fake.PrivateMethodStruct) bool {
                return false
            })
            defer patches.Reset()
            result := f.Happy()
            So(result, ShouldEqual, "unhappy")
        })

        Convey("patch private value method in the different package", func() {
            s := fake.PrivateMethodStruct{}
            patches := ApplyPrivateMethod(s, "haveEaten", func(_ fake.PrivateMethodStruct) bool {
                return false
            })
            defer patches.Reset()
            result := s.AreYouHungry()
            So(result, ShouldEqual, "I am hungry")
        })

        Convey("repeat patch same method", func() {
            var s *fake.PrivateMethodStruct
            patches := ApplyPrivateMethod(s, "ok", func(_ *fake.PrivateMethodStruct) bool {
                return false
            })
            result := s.Happy()
            So(result, ShouldEqual, "unhappy")

            patches.ApplyPrivateMethod(s, "ok", func(_ *fake.PrivateMethodStruct) bool {
                return true
            })
            result = s.Happy()
            So(result, ShouldEqual, "happy")

            patches.Reset()
            result = s.Happy()
            So(result, ShouldEqual, "unhappy")
        })
    })
yourenawo commented 2 years ago

问题已经解决。

IAOTW commented 2 years ago

这个是private method的mock,可以为私有函数mock吗

agiledragon commented 2 years ago

这个是private method的mock,可以为私有函数mock吗

不可以