使用xgo在单测中进行Mock

简介

xgo是一个使用纯go实现的单元测试框架,集成了Mock, Trace, Trap等功能。
xgo的项目地址: https://github.com/xhd2015/xgo

使用步骤

  1. 首先安装xgo
go install github.com/xhd2015/xgo/cmd/xgo@latest
  1. 创建一个demo工程
mkdir demo
cd demo
go mod init demo
  1. 将下面的内容添加到文件demo_test.go中:
package demo

import (
	"testing"

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

func greet(s string) string {
	return "hello " + s
}

func TestPatchFunc(t *testing.T) {
	mock.Patch(greet, func(s string) string {
		return "mock " + s
	})

	res := greet("world")
	if res != "mock world" {
		t.Fatalf("expect patched result to be %q, actual: %q", "mock world", res)
	}
}
  1. 获取依赖
go get github.com/xhd2015/xgo/runtime
  1. 执行单测
xgo test -v ./

输出:

=== RUN   TestFuncMock
--- PASS: TestFuncMock (0.00s)
PASS
ok      demo

如果使用go运行上面的代码, 它会失败:

go test -v ./

输出:

WARNING: failed to link __xgo_link_on_init_finished(requires xgo).
WARNING: failed to link __xgo_link_on_goexit(requires xgo).
=== RUN   TestFuncMock
WARNING: failed to link __xgo_link_set_trap(requires xgo).
WARNING: failed to link __xgo_link_init_finished(requires xgo).
    demo_test.go:21: expect MyFunc() to be 'mock func', actual: my func
--- FAIL: TestFuncMock (0.00s)
FAIL
FAIL    demo    0.771s
FAIL

这是因为要实现Mock功能,需要使用xgo作为-toolexec的参数,具体原理参见文章xgo: golang基于-toolexec实现猴子补丁

Mock的使用概览

github.com/xhd2015/xgo/runtime/mock提供了以下2个主要的API,它们的功能相同,入参有所区别:

  • Patch(fn,replacer) - 第二个参数replacer是一个函数,用来替换第一个函数fn
  • Mock(fn, interceptor) - 第二个参数interceptor是一个拦截器,用来拦截第一个函数fn

它们可用于不同的场景,当你只需要简单替换时,使用Patch, 当你需要实现通用的拦截器时,使用Mock.

Mock的例子:

package demo

import (
	"context"
	"testing"

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

func MyFunc() string {
	return "my func"
}
func TestMock(t *testing.T) {
	mock.Mock(MyFunc, func(ctx context.Context, fn *core.FuncInfo, args core.Object, results core.Object) error {
		results.GetFieldIndex(0).Set("mock func")
		return nil
	})
	text := MyFunc()
	if text != "mock func" {
		t.Fatalf("expect MyFunc() to be 'mock func', actual: %s", text)
	}
}

Patch的例子:

package demo

import (
	"context"
	"testing"

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

func MyFunc() string {
	return "my func"
}
func TestPatch(t *testing.T) {
	mock.Patch(MyFunc, func() string {
		return "mock func"
	})
	text := MyFunc()
	if text != "mock func" {
		t.Fatalf("expect MyFunc() to be 'mock func', actual: %s", text)
	}
}
  • 9
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值