在实际中我们遇到的场景往往会比较复杂,无论我们的代码是作为server端对外提供服务或者还是我们依赖别人提供的网络服务(调用别人提供的API接口)的场景,我们通常都不想在测试过程中真正的建立网络连接。接下来就专门介绍如何在上述两种场景下mock网络测试。
httptest 
在Web开发场景下的单元测试,如果涉及到HTTP请求推荐大家使用Go标准库 net/http/httptest 进行测试,能够显著提高测试效率。
在这一小节,我们以常见的gin框架为例,演示如何为http server编写单元测试。
假设我们的业务逻辑是搭建一个http server端,对外提供HTTP服务。我们编写了一个helloHandler函数,用来处理用户请求。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 package  httptestimport  ("fmt" "net/http" "github.com/gin-gonic/gin" type  Person struct  {string  `json:"name"` func  helloHandler (c *gin.Context) var  p Personif  err := c.ShouldBindJSON(&p); err != nil  {"msg" : "we need a name" ,return "msg" : fmt.Sprintf("hello %s" , p.Name),func  SetupRouter () "/hello" , helloHandler)return  router
现在我们需要为helloHandler函数编写单元测试,这种情况下我们就可以使用httptest这个工具mock一个HTTP请求和响应记录器,让我们的server端接收并处理我们mock的HTTP请求,同时使用响应记录器来记录server端返回的响应内容。
单元测试的示例代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 package  httptestimport  ("encoding/json" "net/http" "net/http/httptest" "strings" "testing" "github.com/stretchr/testify/assert" func  Test_helloHandler (t *testing.T) struct  {string string string "base case" , `{"name": "serendipity"}` , "hello serendipity" },"bad case" , "" , "we need a name" },for  _, tt := range  tests {func (t *testing.T) "POST" ,                       "/hello" ,                     var  resp map [string ]string byte (w.Body.String()), &resp)"msg" ]) 
终端运行go test ./httptest -v执行单元测试,查看测试结果。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 === RUN   Test_helloHandler"debug"  mode. Switch to "release"  mode in production.3  handlers)2024 /04 /15  - 14 :30 :08  | 200  |            0 s |       192.0 .2 .1  | POST     "/hello" 2024 /04 /15  - 14 :30 :08  | 200  |            0 s |       192.0 .2 .1  | POST     "/hello" 0.01 s)0.01 s)0.00 s)0.124 s
通过这个示例我们就掌握了如何使用httptest在HTTP Server服务中为请求处理函数编写单元测试了。
gock 
上面的示例介绍了如何在HTTP Server服务类场景下为请求处理函数编写单元测试,那么如果我们是在代码中请求外部API的场景(比如通过API调用其他服务获取返回值)又该怎么编写单元测试呢?
例如,我们有以下业务逻辑代码,依赖外部API:http://your-api.com/post 提供的数据。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 package  apiimport  ("bytes" "encoding/json" "io/ioutil" "net/http" type  ReqParam struct  {int  `json:"x"` type  Result struct  {int  `json:"value"` func  GetResultByAPI (x, y int ) int  {"http://your-api.com/post" ,"application/json" ,if  err != nil  {return  -1 var  ret Resultif  err := json.Unmarshal(body, &ret); err != nil  {return  -1 return  ret.Value + y
在对类似上述这类业务代码编写单元测试的时候,如果不想在测试过程中真正去发送请求或者依赖的外部接口还没有开发完成时,我们可以在单元测试中对依赖的API进行mock。
这里推荐使用gock 这个库。
安装 
1 go  get -u gopkg.in/h2non/gock
使用 
使用gock对外部API进行mock,即mock指定参数返回约定好的响应内容。 下面的代码中mock了两组数据,组成了两个测试用例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 package  apiimport  ("github.com/h2non/gock" "github.com/stretchr/testify/assert" "testing" func  TestGetResultByAPI (t *testing.T) defer  gock.Off() "http://your-api.com" )."/post" )."json" ).map [string ]int {"x" : 1 }).200 ).map [string ]int {"value" : 100 })1 , 1 )101 )"http://your-api.com" )."/post" )."json" ).map [string ]int {"x" : 2 }).200 ).map [string ]int {"value" : 200 })2 , 2 )202 )
执行上面写好的单元测试,看一下测试结果。
1 2 3 4 === RUN   TestGetResultByAPI0.00 s)0.123 s
测试结果和预期的完全一致。