{"id":22408001,"url":"https://github.com/sjqzhang/gmock","last_synced_at":"2025-07-04T19:04:50.468Z","repository":{"id":42179218,"uuid":"486981412","full_name":"sjqzhang/gmock","owner":"sjqzhang","description":"Mocking utility for Go testing, Support Redis, Http, Gorm,Xorm, DockerService （There is no need to modify existing code）.  一个可以不用改变现在代码就可以进行go单元测试的库，支持Redis,Http,Gorm,DockerService (可以用Docker容器支持)模拟。","archived":false,"fork":false,"pushed_at":"2023-03-28T08:50:27.000Z","size":7294,"stargazers_count":11,"open_issues_count":0,"forks_count":6,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-07T08:11:44.571Z","etag":null,"topics":["gmock","gomock","gorm","gounmock","http","http-mock","mock","mock-http","mock-redis","mock-server","mock-sqite","redis","testing","unmock"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sjqzhang.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-04-29T13:25:02.000Z","updated_at":"2023-12-14T12:24:22.000Z","dependencies_parsed_at":"2024-06-19T02:58:14.633Z","dependency_job_id":"3ddd90fe-2574-4a1f-9e8c-cf4b3ab27eb4","html_url":"https://github.com/sjqzhang/gmock","commit_stats":{"total_commits":136,"total_committers":2,"mean_commits":68.0,"dds":0.007352941176470562,"last_synced_commit":"1fcc89f2aa7d5bd1232f522bbe3f38c1185d2dd9"},"previous_names":[],"tags_count":32,"template":false,"template_full_name":null,"purl":"pkg:github/sjqzhang/gmock","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sjqzhang%2Fgmock","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sjqzhang%2Fgmock/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sjqzhang%2Fgmock/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sjqzhang%2Fgmock/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sjqzhang","download_url":"https://codeload.github.com/sjqzhang/gmock/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sjqzhang%2Fgmock/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":263603137,"owners_count":23487211,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["gmock","gomock","gorm","gounmock","http","http-mock","mock","mock-http","mock-redis","mock-server","mock-sqite","redis","testing","unmock"],"created_at":"2024-12-05T11:16:06.994Z","updated_at":"2025-07-04T19:04:50.447Z","avatar_url":"https://github.com/sjqzhang.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"## 说明\n\n\u003e gmock主要是为了简化单元测试而设计。\n\n## 原理\n\n\u003e 对常用的服务本地内存实现。\n\n## 目标\n\n\u003e 不改变现有代码的情况下，能快速对原有代码进行单元测试(叫集成测试更准确)。\n\n## [与传统做法对比](Notice.md)\n\n## [实操视频](https://www.bilibili.com/video/BV1Eg4y1b73F)https://www.bilibili.com/video/BV1Eg4y1b73F\n## [实操项目](https://github.com/sjqzhang/gin-demo)https://github.com/sjqzhang/gin-demo\n\n## 示例\n\n```go\npackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"github.com/jinzhu/gorm\"\n\t\"github.com/sjqzhang/gmock\"\n\t\"github.com/sjqzhang/gmock/mockdb\"\n\t\"github.com/sjqzhang/gmock/mockdocker\"\n\t_ \"gorm.io/driver/mysql\"\n\tgormv2 \"gorm.io/gorm\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"time\"\n\t\"xorm.io/xorm\"\n)\n\ntype User struct {\n\tId   int    `json:\"id\"`\n\tName string `json:\"name\"`\n\tAge  int    `json:\"age\"`\n}\n\nfunc main() {\n\ttestMockGORM()\n\ttestMockGORMV2()\n\ttestMockXORM()\n\ttestMockRedis()\n\ttestMockHttpServer()\n\ttestMockDocker()\n\ttestDBUtil()\n\n}\n\nfunc testMockGORM() {\n\tvar db *gorm.DB\n\tmockdb.DBType = \"mysql\"\n\tmock := gmock.NewMockGORM(\"example\", func(gorm *mockdb.MockGORM) {\n\t\tdb = gorm.GetGormDB()\n\t})\n\tfmt.Println(mock.GetDSN())\n\t//mock.RegisterModels(\u0026User{})\n\tmock.InitSchemas(`CREATE TABLE user (\n                           id bigint(20) unsigned NOT NULL AUTO_INCREMENT,\n                           age int(3) DEFAULT NULL,\n                           name varchar(255) DEFAULT NULL COMMENT '名称',\n                           PRIMARY KEY (id)\n) ENGINE=InnoDB ;`)\n\tmock.ResetAndInit()\n\n\tvar user User\n\terr := db.Where(\"id=?\", 1).Find(\u0026user).Error\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif user.Id != 1 {\n\t\tpanic(fmt.Errorf(\"testMockGORM error\"))\n\t}\n\n}\n\nfunc testDBUtil() {\n\tutil := gmock.NewDBUtil()\n\tutil.RunMySQLServer(\"test\", 33333, false)\n\tdb, err := gorm.Open(\"mysql\", \"user:pass@tcp(127.0.0.1:33333)/test?charset=utf8mb4\u0026parseTime=True\u0026loc=Local\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tsqlText := util.ReadFile(\"./example/ddl.txt\")\n\tfor _, s := range util.ParseSQLText(sqlText) {\n\t\tfmt.Println(db.Exec(s))\n\t}\n\tfmt.Println(util.QueryListBySQL(db.DB(), \"select * from project\"))\n}\n\nfunc testMockGORMV2() {\n\tmockdb.DBType = \"mysql\"\n\tvar db *gormv2.DB\n\tmock := gmock.NewMockGORMV2(\"example\", func(orm *mockdb.MockGORMV2) {\n\t\tdb = orm.GetGormDB()\n\t})\n\t//注册模型\n\tmock.RegisterModels(\u0026User{})\n\t//初始化数据库及表数据\n\tmock.ResetAndInit()\n\tmock.ResetAndInit()\n\t//db := mock.GetGormDB()\n\tvar user User\n\terr := db.Where(\"id=?\", 1).Find(\u0026user).Error\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif user.Id != 1 {\n\t\tpanic(fmt.Errorf(\"testMockGORMV2 error\"))\n\t}\n\n}\n\nfunc testMockRedis() {\n\tserver := gmock.NewMockRedisServer(63790)\n\tclient := server.GetRedisClient()\n\tctx := context.Background()\n\tkey := \"aa\"\n\tvalue := \"aa value\"\n\tpool := server.GetRedigoPool()\n\tconn := pool.Get()\n\tdefer conn.Close()\n\trep, err := conn.Do(\"set\", key, value)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(rep)\n\t//client.Set(ctx, key, value, time.Second*10)\n\tcmd := client.Get(ctx, key)\n\tif cmd.Val() != value {\n\t\tpanic(\"testMockRedis error\")\n\t}\n\n}\n\nfunc testMockHttpServer() {\n\t// 只支持 http 不支持 https\n\tserver := gmock.NewMockHttpServer(\"./\", []string{\"www.baidu.com\", \"www.jenkins.org\"})\n\tserver.InitMockHttpServer()\n\t//server.SetReqRspHandler(func(req *mockhttp.Request, rsp *mockhttp.Response) {\n\t//\treq.Method = \"GET\"\n\t//\treq.Endpoint = \"/HelloWorld\"\n\t//\treq.Host = \"www.baidu.com\"\n\t//\trsp.Body = \"xxxxxxxxx bbbb\"\n\t//})\n\tresp, err := http.Get(\"http://www.baidu.com/hello/xxx\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif string(data) != \"hello baidu\" {\n\t\tpanic(fmt.Errorf(\"testMockHttpServer error\"))\n\t}\n}\n\nfunc testMockXORM() {\n\tvar engine *xorm.Engine\n\tmockdb.DBType = \"mysql\"\n\tmock := gmock.NewMockXORM(\"example\", func(orm *mockdb.MockXORM) {\n\t\tengine = orm.GetXORMEngine()\n\t})\n\tmock.RegisterModels(\u0026User{})\n\n\tmock.ResetAndInit()\n\tdb := mock.GetXORMEngine()\n\tvar user User\n\t_, err := db.Where(\"id=?\", 1).Get(\u0026user)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif user.Id != 1 {\n\t\tpanic(fmt.Errorf(\"testMockXORM error\"))\n\t}\n}\n\nfunc testMockDocker() {\n\tmock := mockdocker.NewMockDockerService()\n\tdefer mock.Destroy()\n\terr := mock.InitContainerWithCmd(func(cmd *string) {\n\t\t//  注意：容器必须后台运行，否则会挂起，程序不会继续执行,所以要保证你的容器后台运行不退出\n\t\t*cmd = \"docker run --name some-mysql  -p 3308:3306 -e MYSQL_ROOT_PASSWORD=root -d mysql:5.7\"\n\t})\n\tfmt.Println(err)\n\tif !mock.WaitForReady(\"wget 127.0.0.1:3308 -O -\", time.Second*50) {\n\t\tpanic(fmt.Errorf(\"mysql start fail\"))\n\t}\n\tfmt.Println(\"mysql start success\")\n\n}\n\n```\n\n## 生成覆盖率及测试报告\n\n```bash\n\ngo test -timeout 0 -covermode=count -coverprofile=coverage.out  -run=\"^Test\" -coverpkg=package1,package2  \n\ngo tool cover -html=coverage.out -o coverage.html\n\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsjqzhang%2Fgmock","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsjqzhang%2Fgmock","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsjqzhang%2Fgmock/lists"}