Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ZYLLCY opened this issue Dec 13, 2023 · 1 comment
Open

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

ZYLLCY opened this issue Dec 13, 2023 · 1 comment

Comments

@ZYLLCY
Copy link

ZYLLCY commented Dec 13, 2023

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

@ZYLLCY ZYLLCY changed the title how to mock method which as a param in another method how to mock func which as a param in another func Dec 13, 2023
@xhd2015
Copy link

xhd2015 commented Mar 22, 2024

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants