Skip to content

Commit

Permalink
api test
Browse files Browse the repository at this point in the history
  • Loading branch information
morvanzhou committed Nov 15, 2019
1 parent fedaeba commit 71b61e5
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 0 deletions.
48 changes: 48 additions & 0 deletions 6apimock/api.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package _apimock

import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
)

type getResp struct {
Return int
}

func GetApiAddOne() int {
resp, err := http.Get("http://your-api.com/get")
if err != nil {
return 0
}
body, _ := ioutil.ReadAll(resp.Body)
var resp_ getResp
if err := json.Unmarshal(body, &resp_); err != nil {
return 0
}
return resp_.Return + 1
}

type postReq struct {
Param int
}
type postResp struct {
Return int
}

func PostApiAddOne(x int) int {
query := &postReq{Param: x}
b, _ := json.Marshal(query)

resp, err := http.Post("http://your-api.com/post", "application/json", bytes.NewBuffer(b))
if err != nil {
return 0
}
body, _ := ioutil.ReadAll(resp.Body)
var resp_ postResp
if err := json.Unmarshal(body, &resp_); err != nil {
return 0
}
return resp_.Return + 1
}
49 changes: 49 additions & 0 deletions 6apimock/api_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package _apimock_test

import (
_apimock "github.com/morvanzhou/unittest-demo/6apimock"
"github.com/stretchr/testify/assert"
"gopkg.in/h2non/gock.v1"
"testing"
)

func TestGetApiAddOne(t *testing.T) {
defer gock.Off()

gock.New("http://your-api.com").
Get("/get"). // get 方法
Reply(200).
JSON(map[string]int{"Return": 1}) // 回复 1

res := _apimock.GetApiAddOne()

assert.Equal(t, res, 2) // 1 + 1 = 2

assert.True(t, gock.IsDone())
}

func TestPostApiAddOne(t *testing.T) {
defer gock.Off()

gock.New("http://your-api.com").
Post("/post"). // post 方法
MatchType("json").
JSON(map[string]int{"Param": 1}). // 请求为 1 时
Reply(200).
JSON(map[string]int{"Return": 1}) // 回复 1

res := _apimock.PostApiAddOne(1) // 发送请求 1
assert.Equal(t, res, 2) // 1 + 1 = 2

gock.New("http://your-api.com").
Post("/post"). // post 方法
MatchType("json").
JSON(map[string]int{"Param": 2}). // 请求为 2 时
Reply(200).
JSON(map[string]int{"Return": 2}) // 回复 2

res = _apimock.PostApiAddOne(2) // 发送请求 2
assert.Equal(t, res, 3) // 2 + 1 = 3

assert.True(t, gock.IsDone())
}

0 comments on commit 71b61e5

Please sign in to comment.