github.com/agiledragon/gomonkey/v2@v2.11.1-0.20240427155748-d56c6823ec17/test/apply_private_method_test.go (about)

     1  package test
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/agiledragon/gomonkey/v2/test/fake"
     7  
     8  	. "github.com/smartystreets/goconvey/convey"
     9  
    10  	. "github.com/agiledragon/gomonkey/v2"
    11  )
    12  
    13  func TestApplyPrivateMethod(t *testing.T) {
    14  	Convey("TestApplyPrivateMethod", t, func() {
    15  		Convey("patch private pointer method in the different package", func() {
    16  			f := new(fake.PrivateMethodStruct)
    17  			var s *fake.PrivateMethodStruct
    18  			patches := ApplyPrivateMethod(s, "ok", func(_ *fake.PrivateMethodStruct) bool {
    19  				return false
    20  			})
    21  			defer patches.Reset()
    22  			result := f.Happy()
    23  			So(result, ShouldEqual, "unhappy")
    24  		})
    25  
    26  		Convey("patch private value method in the different package", func() {
    27  			s := fake.PrivateMethodStruct{}
    28  			patches := ApplyPrivateMethod(s, "haveEaten", func(_ fake.PrivateMethodStruct) bool {
    29  				return true
    30  			})
    31  			defer patches.Reset()
    32  			result := s.AreYouHungry()
    33  			So(result, ShouldEqual, "I am full")
    34  		})
    35  
    36  		Convey("repeat patch same method", func() {
    37  			var s *fake.PrivateMethodStruct
    38  			patches := ApplyPrivateMethod(s, "ok", func(_ *fake.PrivateMethodStruct) bool {
    39  				return false
    40  			})
    41  			result := s.Happy()
    42  			So(result, ShouldEqual, "unhappy")
    43  
    44  			patches.ApplyPrivateMethod(s, "ok", func(_ *fake.PrivateMethodStruct) bool {
    45  				return true
    46  			})
    47  			result = s.Happy()
    48  			So(result, ShouldEqual, "happy")
    49  
    50  			patches.Reset()
    51  			result = s.Happy()
    52  			So(result, ShouldEqual, "unhappy")
    53  		})
    54  	})
    55  
    56  }