github.com/tencent/goom@v1.0.1/mocker_generics_test.go (about)

     1  //go:build go1.18
     2  // +build go1.18
     3  
     4  // Package mocker_test mock单元测试包
     5  // 泛型相关的mock实现,特性支持参照来源于: https://taoshu.in/go/monkey/generic.html
     6  package mocker_test
     7  
     8  import (
     9  	"fmt"
    10  	"testing"
    11  
    12  	"github.com/stretchr/testify/suite"
    13  	"github.com/tencent/goom"
    14  )
    15  
    16  type GT[T any] struct {
    17  }
    18  
    19  //go:noinline
    20  func (gt *GT[T]) Hello() T {
    21  	var t T
    22  	fmt.Println("")
    23  	return t
    24  }
    25  
    26  //go:noinline
    27  func Hello[T int | string]() T {
    28  	var t T
    29  	fmt.Println("")
    30  	return t
    31  }
    32  
    33  // TestUnitGenericsSuite 测试入口
    34  func TestUnitGenericsSuite(t *testing.T) {
    35  	// 开启 debug
    36  	// 1.可以查看 apply 和 reset 的状态日志
    37  	// 2.查看 mock 调用日志
    38  	mocker.OpenDebug()
    39  	suite.Run(t, new(mockerTestGenericsSuite))
    40  }
    41  
    42  type mockerTestGenericsSuite struct {
    43  	suite.Suite
    44  }
    45  
    46  // TestGenericsMethod 测试泛型方法调用
    47  func (s *mockerTestGenericsSuite) TestGenericsMethod() {
    48  	s.Run("success", func() {
    49  		myMocker := mocker.Create()
    50  		defer myMocker.Reset()
    51  
    52  		myMocker.Struct(&GT[string]{}).Method("Hello").
    53  			Return("hello")
    54  		myMocker.Struct(&GT[int]{}).Method("Hello").
    55  			Return(1)
    56  
    57  		var gt *GT[string]
    58  		s.Equal("hello", gt.Hello(), "foo mock check")
    59  		var gt1 *GT[int]
    60  		s.Equal(1, gt1.Hello(), "foo mock check")
    61  	})
    62  }
    63  
    64  // TestGenericsMethodFunc 测试泛型方法函数调用
    65  func (s *mockerTestGenericsSuite) TestGenericsMethodFunc() {
    66  	s.Run("success", func() {
    67  		myMocker := mocker.Create()
    68  		defer myMocker.Reset()
    69  
    70  		hello1 := (&GT[string]{}).Hello
    71  		myMocker.Func(hello1).Return("hello")
    72  		hello2 := (&GT[int]{}).Hello
    73  		myMocker.Func(hello2).Return(1)
    74  
    75  		s.Equal("hello", hello1(), "foo mock check")
    76  		s.Equal(1, hello2(), "foo mock check")
    77  	})
    78  }
    79  
    80  // TestGenericsFunc 测试泛型函数调用
    81  func (s *mockerTestGenericsSuite) TestGenericsFunc() {
    82  	s.Run("success", func() {
    83  		myMocker := mocker.Create()
    84  		defer myMocker.Reset()
    85  
    86  		myMocker.Func(Hello[string]).Return("hello")
    87  		myMocker.Func(Hello[int]).Return(1)
    88  
    89  		s.Equal("hello", Hello[string](), "foo mock check")
    90  		s.Equal(1, Hello[int](), "foo mock check")
    91  	})
    92  }