在上面的案例中,针对 interface 我们通过 gomock 来帮我们自动生成符合接口的类后,只需要通过 gomock 约定的 API 就能够对 interface 中的函数按期望和需要来模拟,这个很好理解。 对于函数以及方法的 mock,由于本身代码逻辑已经声明好(go 是静态强类型语言),我们很难通过编码的方式将其 mock 掉,这对我们做单元测...
packagestoreimport("database/sql/driver""github.com/DATA-DOG/go-sqlmock""github.com/gin-gonic/gin""github.com/jinzhu/gorm""github.com/stretchr/testify/assert""net/http/httptest""testing")typeRepoCommitAndCRCountMetricstruct{ ProjectIDuint`json:"project_id"`RepoCommitCountuint`json:"repo_commit...
安装go install github.com/golang/mock/mockgen@v1.6.0 基本case 代码 首先我们还是基于上一次的例子,这里给出上一次例子中所用到的接口 代码语言:javascript 代码运行次数:0 复制Cloud Studio 代码运行 package service import ( "context" "fmt" "go-demo/m/unit-test/entity" ) type UserRepo interface {...
packagerepoimport("database/sql""fmt""testing""time"_"github.com/go-sql-driver/mysql""github.com/ory/dockertest/v3""github.com/ory/dockertest/v3/docker""go-demo/m/unit-test/entity""xorm.io/xorm""xorm.io/xorm/schemas")typeTestDBSettingstruct{ DriverstringImageNamestringImageVersionstringENV...
因此,对于assert(断言)工具,可以选择 testify 或 convery,笔者这里选择了 testify。对于mock(模拟)工具,笔者这里选择了 gomock 和 gomonkey。关于 mock 工具同时使用 gomock 和 gomonkey,这里跟 Golang 的语言特性有关,下面会详细的说明。 完善测试用例
packagecontrollerimport("context""github.com/gin-gonic/gin""go-demo/m/unit-test/entity")//go:generate mockgen -source=./user.go -destination=../mock/user_service_mock.go -package=mocktypeUserServiceinterface{ AddUser(ctx context.Context, usernamestring) (errerror) ...
func TestBlobObjects(t *testing.T) { tests := map[string]struct { client *MockClient ... }{ "Test case 1": { client: &MockClient{ MockListBlobObjects: ..., }, ... }, ... for testName, test := range tests { blobs, err := (test.client, clientOptions{}) // ...
go install github.com/golang/mock/mockgen@v1.6.0 复制 基本case 代码 首先我们还是基于上一次的例子,这里给出上一次例子中所用到的接口 package serviceimport("context""fmt""go-demo/m/unit-test/entity")type UserRepointerface{AddUser(ctx context.Context,user*entity.User)(err error)DelUser(ctx con...
如果13~16行输出的结果和18~21行的结果相对应,go test就会PASS,否则就会FAIL,并打印出实际输出和期望输出。 5.Go的Mock方法 5.1 Mock的简介 mock,中文译名为“模仿,假的”,顾名思义就是构建一个模拟对象,来替换掉一些需要在特定环境下触发的服务,使其可以在不修改原服务的前提下达到测试的目的。本文介绍一种...
现在我们需要为helloHandler函数编写单元测试,这种情况下我们就可以使用httptest这个工具mock一个HTTP请求和响应记录器,让我们的server端接收并处理我们mock的HTTP请求,同时使用响应记录器来记录server端返回的响应内容。 单元测试的示例代码如下: ...