使用httptest網絡測試

功能代碼,可能提供方出現問題json

package htest

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

const (
	ADDRESS = "shenzhen"
)

type Weather struct {
	City    string `json:"city"`
	Date    string `json:"date"`
	TemP    string `json:"temP"`
	Weather string `json:"weather"`
}

func GetWeatherInfo(api string) ([]Weather, error) {
	url := fmt.Sprintf("%s/weather?city=%s", api, ADDRESS)
	resp, err := http.Get(url)

	if err != nil {
		return []Weather{}, err
	}

	if resp.StatusCode != http.StatusOK {
		return []Weather{}, fmt.Errorf("Resp is didn't 200 OK:%s", resp.Status)
	}
	bodybytes, _ := ioutil.ReadAll(resp.Body)
	personList := make([]Weather, 0)

	err = json.Unmarshal(bodybytes, &personList)

	if err != nil {
		return []Weather{}, fmt.Errorf("Decode data fail")
	}
	return personList, nil
}
複製代碼

測試代碼api

package htest

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"
)

var weatherResp = []Weather{
	{
		City:    "shenzhen",
		Date:    "10-22",
		TemP:    "15℃~21℃",
		Weather: "rain",
	},
	{
		City:    "guangzhou",
		Date:    "10-22",
		TemP:    "15℃~21℃",
		Weather: "sunny",
	},
	{
		City:    "beijing",
		Date:    "10-22",
		TemP:    "1℃~11℃",
		Weather: "snow",
	},
}
var weatherRespBytes, _ = json.Marshal(weatherResp)

func TestGetInfoUnauthorized(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	    // 隨機啓動的服務器,將請求使用下面的代碼處理
		w.WriteHeader(http.StatusUnauthorized)
		w.Write(weatherRespBytes)
		if r.Method != "GET" {
			t.Errorf("Except 'Get' got '%s'", r.Method)
		}

		if r.URL.EscapedPath() != "/weather" {
			t.Errorf("Except to path '/person',got '%s'", r.URL.EscapedPath())
		}
		r.ParseForm()
		topic := r.Form.Get("city")
		if topic != "shenzhen" {
			t.Errorf("Except rquest to have 'city=shenzhen',got '%s'", topic)
		}
	}))
	defer ts.Close()
	api := ts.URL // 端口隨機變化,地址爲當前執行機器的地址
	fmt.Printf("Url:%s\n", api)
	resp, err := GetWeatherInfo(api) // 問題存在即傳遞當前的地址
	if err != nil {
		t.Error("ERR:", err)
	} else {
		fmt.Println("resp:", resp)
	}
}
複製代碼
相關文章
相關標籤/搜索