golang单测集成简化工具mockit【开源库】
func TestMain(m *testing.M) {
var err error
// interface intercept agent
// 初始化kit,一个new搞定
kit, err = New(mockinterface.NewMockDemoInterface)
if err != nil {
panic(err)
}
{ // 初始化mock service
// http.client需要InterceptHttpClient一下
cli := http.DefaultClient
kit.InterceptHttpClient(cli)
// 初始化的mock interface实例获取后需要反射一下
iImpl := kit.GetInterfaceClient("MockDemoInterface")
iface := iImpl.(*mockinterface.MockDemoInterface)
httpCli := mockhttp.NewMockHttpCli()
kit.InterceptHttpClient(httpCli.Client())
// 拦截
srv = &mockSrv{
es: mockes.NewMockEs(cli),
httpCli: httpCli,
iface: iface,
redis: mockredis.NewMockRedis(kit.RedisAddr()), // redis只要使用mockit返回的server地址
sql: mocksql.NewSqlDao(kit.Gorm2DB()), // mysql只需要替换gormDB
}
}
os.Exit(m.Run())
}
func TestDemo(t *testing.T){
// http mock
p := mockit.NewExpectParam().WithMethod("GET").
WithPath("http://sh-gateway.shihuo.cn/v4/services/sh-goodsinnerapi/style/get").
WithReturns(mockResp)
kit.HttpExpect(p, t)
// interface
p := mockit.NewExpectParam().
WithPath(labelLib).
WithMethod("BatchSalesSoarTagByStyleIds").
WithReturns([]*cbo.BatchGoodsSalesSoarTagModel{
{
StyleId: int64(collects[0].StyleId),
TagId: -1,
Value: 10000,
},
}, nil)
kit.InterfaceExpect(p, t)
// MySQL
p := mockit.NewExpectParam().
WithMethod("SELECT (.+) FROM `trd_user_collect_goods` WHERE user_id = (.+)$").
WithArgs(param.UserId, false).WithReturns(collects)
kit.MysqlQueryExpect(p, t)
}