golang-模拟http请求测试

直接给个例子,方便日常开发接口请求

创建个测试文体
vim test/test_request.go
编辑一下代码

package test

import (
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestCustomClient(t *testing.T) {
	// 创建一个模拟的 HTTP 服务器
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 设置响应头
		w.Header().Set("Content-Type", "application/json") // 必须在 WriteHeader 和 Write 之前调用
		// 设置响应状态码
		w.WriteHeader(http.StatusOK)
		// 返回响应内容
		w.Write([]byte(`{"message": "Hi! golang"}`))
	}))
	defer server.Close() // 测试结束后关闭服务器

	// 发起请求到模拟的服务器
	resp, err := http.Get(server.URL)
	if err != nil {
		t.Fatalf("请求失败: %v", err)
	}
	defer resp.Body.Close()

	// 检查响应状态码
	if resp.StatusCode != http.StatusOK {
		t.Errorf("期望状态码 200,实际得到 %d", resp.StatusCode)
	}

	// 检查响应头
	contentType := resp.Header.Get("Content-Type")
	if contentType != "application/json" {
		t.Errorf("期望 Content-Type 为 application/json,实际得到 %s", contentType)
	}

	// 读取响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Fatalf("读取响应体失败: %v", err)
	}

	// 检查响应内容
	expectedBody := `{"message": "Hi! golang!"}`
	if string(body) != expectedBody {
		t.Errorf("期望响应体 %s,实际得到 %s", expectedBody, string(body))
	}
}

进行测试验证
go test test_request.go

正常通过显示如下:
% go test test/request_test.go
ok command-line-arguments 0.536s

如果想要输出打印内容到命令行,可以加下参数-v :
go test test_request.go -v
如果想要指定测试文件内到某个测试函数,可以加下参数-run :
go test test_request.go -v -run ^函数名称$

其他参数:
使用 -bench 参数运行基准测试。
使用 -tags 参数运行带有标签的测试。
使用 -cover 参数生成覆盖率报告。

posted @   洪先森  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示