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 参数生成覆盖率报告。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话