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

     1  // Package mocker_test 对 mocker 包的测试
     2  // 当前文件实现了对 mocker.go 的单测
     3  package mocker_test
     4  
     5  import (
     6  	"errors"
     7  	"fmt"
     8  	"math/rand"
     9  	"testing"
    10  	"time"
    11  
    12  	"github.com/stretchr/testify/suite"
    13  	"github.com/tencent/goom/test"
    14  )
    15  
    16  // TestUnitAmd64TestSuite 测试入口
    17  func TestUnitAmd64TestSuite(t *testing.T) {
    18  	// 开启 debug
    19  	// 1.可以查看 apply 和 reset 的状态日志
    20  	// 2.查看 mock 调用日志
    21  	mocker.OpenDebug()
    22  	suite.Run(t, new(mockerTestAmd64Suite))
    23  }
    24  
    25  type mockerTestAmd64Suite struct {
    26  	suite.Suite
    27  	fakeErr error
    28  }
    29  
    30  func (s *mockerTestAmd64Suite) SetupTest() {
    31  	s.fakeErr = errors.New("fake error")
    32  }
    33  
    34  // TestCallOrigin 测试调用原函数 mock return
    35  func (s *mockerTestAmd64Suite) TestCallOrigin() {
    36  	s.Run("success", func() {
    37  		// 定义原函数,用于占位,实际不会执行该函数体
    38  		var origin = func(i int) int {
    39  			// 用于占位,实际不会执行该函数体, 但是必须编写
    40  			fmt.Println("only for placeholder, will not call")
    41  			// return 任意值
    42  			return 0
    43  		}
    44  
    45  		mock := mocker.Create()
    46  		mock.Func(test.Foo).Origin(&origin).Apply(func(i int) int {
    47  			originResult := origin(i)
    48  			fmt.Printf("arguments are %v\n", i)
    49  			return originResult + 100
    50  		})
    51  		s.Equal(101, test.Foo(1), "foo mock check")
    52  
    53  		mock.Reset()
    54  		s.Equal(1, test.Foo(1), "foo mock reset check")
    55  	})
    56  }
    57  
    58  // TestUnitSystemFuncApply 测试系统函数的 mock
    59  // 需要加上 -gcflags="-l"
    60  // 在bazel 构建环境下, 因为系统库不支持开启 gcflags=-l ,所以暂不支持系统库中的短函数 mock
    61  func (s *mockerTestAmd64Suite) TestUnitSystemFuncApply() {
    62  	s.Run("success", func() {
    63  		mock := mocker.Create()
    64  		defer mock.Reset()
    65  
    66  		mock.Func(rand.Int31).Return(int32(3))
    67  		date, _ := time.Parse("2006-01-02 15:04:05", "2020-07-30 00:00:00")
    68  		mock.Func(time.Now).Return(date)
    69  
    70  		s.Equal(int32(3), rand.Int31(), "foo mock check")
    71  		s.Equal(date, time.Now(), "foo mock check")
    72  	})
    73  }
    74  
    75  func (s *mockerTestAmd64Suite) TestUnitEmptyMatch() {
    76  	s.Run("empty return", func() {
    77  		mocker.Create().Func(time.Sleep).Return()
    78  		time.Sleep(time.Second)
    79  	})
    80  }