github.com/bytedance/mockey@v1.2.10/mock_var_test.go (about)

     1  /*
     2   * Copyright 2022 ByteDance Inc.
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package mockey
    18  
    19  import (
    20  	"fmt"
    21  	"testing"
    22  
    23  	. "github.com/smartystreets/goconvey/convey"
    24  )
    25  
    26  func TestVarPatchConvey(t *testing.T) {
    27  	b := 1
    28  	a := 10
    29  	PatchConvey("test mock2", t, func() {
    30  		PatchConvey("test mock3", func() {
    31  			MockValue(&a).To(20)
    32  			So(a, ShouldEqual, 20)
    33  			PatchConvey("test mock4", func() {
    34  				MockValue(&a).To(30)
    35  				MockValue(&b).To(40)
    36  				So(b, ShouldEqual, 40)
    37  				So(a, ShouldEqual, 30)
    38  			})
    39  			So(b, ShouldEqual, 1)
    40  		})
    41  		So(b, ShouldEqual, 1)
    42  		So(a, ShouldEqual, 10)
    43  
    44  		PatchConvey("test mock5", func() {
    45  			MockValue(&a).To(30)
    46  			So(a, ShouldEqual, 30)
    47  		})
    48  
    49  		So(a, ShouldEqual, 10)
    50  	})
    51  }
    52  
    53  type testStruct struct {
    54  	a string
    55  	b int
    56  }
    57  
    58  func TestVarStruct(t *testing.T) {
    59  	ttt := &testStruct{
    60  		a: "1",
    61  		b: 2,
    62  	}
    63  	PatchConvey("test mock2", t, func() {
    64  		PatchConvey("test mock3", func() {
    65  			MockValue(&ttt).To(&testStruct{
    66  				a: "2",
    67  				b: 3,
    68  			})
    69  			So(ttt.a, ShouldEqual, "2")
    70  			PatchConvey("test mock3 a", func() {
    71  				MockValue(&ttt).To(&testStruct{
    72  					a: "3",
    73  					b: 3,
    74  				})
    75  				So(ttt.a, ShouldEqual, "3")
    76  			})
    77  			PatchConvey("test mock3 b", func() {
    78  				MockValue(&ttt).To(nil)
    79  				So(ttt, ShouldBeNil)
    80  			})
    81  		})
    82  	})
    83  }
    84  
    85  func (t *testStruct) String() string {
    86  	return t.a
    87  }
    88  
    89  func TestVarStruct2(t *testing.T) {
    90  	Convey("test mock nil", t, func() {
    91  		var ttt fmt.Stringer
    92  		PatchConvey("test mock3", func() {
    93  			MockValue(&ttt).To(&testStruct{
    94  				a: "2",
    95  				b: 3,
    96  			})
    97  			So(ttt.(*testStruct).a, ShouldEqual, "2")
    98  		})
    99  		So(ttt, ShouldBeNil)
   100  	})
   101  }