agiledragon / gomonkey

gomonkey is a library to make monkey patching in unit tests easy
MIT License
1.92k stars 178 forks source link

how to mock func which as a param in another func #154

Open ZYLLCY opened 6 months ago

ZYLLCY commented 6 months ago

how to mock method which as a param in another method

func BeginTx(ctx context.Context, opts *sql.TxOptions, do func(ctx context.Context) exception.CodeError) exception.CodeError {


)

for example, I want mock do method which in BeginTx, thanks for you answer
xhd2015 commented 3 months ago

Hi ZYLLCY, with xgo this should be simple and straightforward:

package main

import (
    "context"
   "testing"

    "github.com/xhd2015/xgo/runtime/core"
    "github.com/xhd2015/xgo/runtime/mock"
)

func TestBeginTx(t *testing.T) {
     // setup mock
     mock.AddFuncInterceptor(BeginTx, func(ctx context.Context, fn *core.FuncInfo, args core.Object, results core.Object) error {
        doArg := args.GetField("do")
        doArg.Set(func(ctx context.Context) exception.CodeError{
            // your mock logic
        })
        return mock.ErrCallOld
    })

     // call the function with previous mock setup
     BeginTx(....)
}

func BeginTx(ctx context.Context, opts *sql.TxOptions, do func(ctx context.Context) exception.CodeError) exception.CodeError{
}

Check https://github.com/xhd2015/xgo for more details!