V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
xhd2015
V2EX  ›  Go 编程语言

xgo:一个基于 IR 重写的 golang mock 库

  •  1
     
  •   xhd2015 · 30 天前 via iPhone · 867 次点击

    最近基于工作需要,在使用了 gomonkey 遇到很多问题之后,并且也担心基于 Assembly 的方式对未来单测维护的不可持续性,开发了 xgo 。

    xgo 基于 IR 中间码重写,更加贴近源代码而不是机器码。所以兼容性比 Assembly 要好很多,功能也更强。

    下面是一个简单的示例:

    package demo
    
    import (
    	"context"
    	"testing"
    
    	"github.com/xhd2015/xgo/runtime/core"
    	"github.com/xhd2015/xgo/runtime/mock"
    )
    
    func MyFunc() string {
    	return "my func"
    }
    func TestFuncMock(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)
    	}
    }
    

    欢迎大家使用和提意见

    项目地址 https://github.com/xhd2015/xgo

    8 条回复
    mightybruce
        1
    mightybruce  
       30 天前   ❤️ 1
    行,关注了。
    xhd2015
        2
    xhd2015  
    OP
       30 天前 via iPhone
    说明一下:该 mock 不需要基于接口进行 monkey ,开箱可用😃
    oceana
        3
    oceana  
       30 天前   ❤️ 1
    点个赞
    xhd2015
        4
    xhd2015  
    OP
       30 天前 via iPhone
    @oceana 感谢,可以一起交流😌
    sophos
        5
    sophos  
       29 天前
    有点意思,和我这个项目的功能有点类似,不过实现思路不太一样 :-)

    https://github.com/go-kod/kod
    xhd2015
        6
    xhd2015  
    OP
       29 天前 via iPhone
    @sophos 目标不一样,这个是单元测试场景,主打无代码侵入,无代码生成
    sophos
        7
    sophos  
       29 天前
    @xhd2015 嗯,我这个是为了优化代码模块设计,同时解决单元测试标准化的问题

    不过个人感觉单元测试的最佳实践还是 mock interface ,patch 不够直观
    xhd2015
        8
    xhd2015  
    OP
       29 天前 via iPhone
    @sophos 哈哈,我持相反的看法
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2910 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 07:48 · PVG 15:48 · LAX 00:48 · JFK 03:48
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.