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

     1  package test
     2  
     3  import (
     4  	"testing"
     5  
     6  	. "github.com/agiledragon/gomonkey/v2"
     7  	"github.com/agiledragon/gomonkey/v2/test/fake"
     8  	. "github.com/smartystreets/goconvey/convey"
     9  )
    10  
    11  func TestApplyMethod(t *testing.T) {
    12  	slice := fake.NewSlice()
    13  	var s *fake.Slice
    14  	Convey("TestApplyMethod", t, func() {
    15  
    16  		Convey("for succ", func() {
    17  			err := slice.Add(1)
    18  			So(err, ShouldEqual, nil)
    19  			patches := ApplyMethod(s, "Add", func(_ *fake.Slice, _ int) error {
    20  				return nil
    21  			})
    22  			defer patches.Reset()
    23  			err = slice.Add(1)
    24  			So(err, ShouldEqual, nil)
    25  			err = slice.Remove(1)
    26  			So(err, ShouldEqual, nil)
    27  			So(len(slice), ShouldEqual, 0)
    28  		})
    29  
    30  		Convey("for already exist", func() {
    31  			err := slice.Add(2)
    32  			So(err, ShouldEqual, nil)
    33  			patches := ApplyMethod(s, "Add", func(_ *fake.Slice, _ int) error {
    34  				return fake.ErrElemExsit
    35  			})
    36  			defer patches.Reset()
    37  			err = slice.Add(1)
    38  			So(err, ShouldEqual, fake.ErrElemExsit)
    39  			err = slice.Remove(2)
    40  			So(err, ShouldEqual, nil)
    41  			So(len(slice), ShouldEqual, 0)
    42  		})
    43  
    44  		Convey("two methods", func() {
    45  			err := slice.Add(3)
    46  			So(err, ShouldEqual, nil)
    47  			defer slice.Remove(3)
    48  			patches := ApplyMethod(s, "Add", func(_ *fake.Slice, _ int) error {
    49  				return fake.ErrElemExsit
    50  			})
    51  			defer patches.Reset()
    52  			patches.ApplyMethod(s, "Remove", func(_ *fake.Slice, _ int) error {
    53  				return fake.ErrElemNotExsit
    54  			})
    55  			err = slice.Add(2)
    56  			So(err, ShouldEqual, fake.ErrElemExsit)
    57  			err = slice.Remove(1)
    58  			So(err, ShouldEqual, fake.ErrElemNotExsit)
    59  			So(len(slice), ShouldEqual, 1)
    60  			So(slice[0], ShouldEqual, 3)
    61  		})
    62  
    63  		Convey("one func and one method", func() {
    64  			err := slice.Add(4)
    65  			So(err, ShouldEqual, nil)
    66  			defer slice.Remove(4)
    67  			patches := ApplyFunc(fake.Exec, func(_ string, _ ...string) (string, error) {
    68  				return outputExpect, nil
    69  			})
    70  			defer patches.Reset()
    71  			patches.ApplyMethod(s, "Remove", func(_ *fake.Slice, _ int) error {
    72  				return fake.ErrElemNotExsit
    73  			})
    74  			output, err := fake.Exec("", "")
    75  			So(err, ShouldEqual, nil)
    76  			So(output, ShouldEqual, outputExpect)
    77  			err = slice.Remove(1)
    78  			So(err, ShouldEqual, fake.ErrElemNotExsit)
    79  			So(len(slice), ShouldEqual, 1)
    80  			So(slice[0], ShouldEqual, 4)
    81  		})
    82  	})
    83  }