在 go 中测试与外部 api 的交互涉及以下步骤:使用 net/http 包设置 http 客户机。使用 httpclient.do 发送 http 请求,提供请求详细信息。断言响应状态码、标题和正文符合预期。

Go 测试:如何测试与外部 API 的交互
在构建可靠的软件时,测试与外部 API 的交互至关重要。在 Go 中,我们可以使用 HTTP 客户机进行这些测试,本文将引导你了解如何有效地实现此功能。
设置 HTTP 客户机
立即学习“go语言免费学习笔记(深入)”;
我们首先设置 HTTP 客户机,用于向 API 发送请求。Go 提供了 net/http 包来轻松实现此目的:
import (
"net/http"
)
var httpClient = http.Client{}发送 HTTP 请求
为了发送 HTTP 请求,我们可以使用 httpClient.Do 函数。它接受一个包含请求详细信息(例如 URL、方法和请求正文)的 *http.Request:
req, err := http.NewRequest("GET", "https://example.com/api/v1/users", nil)
if err != nil {
// 处理错误
}
resp, err := httpClient.Do(req)
if err != nil {
// 处理错误
}断言响应
发送请求后,我们必须断言响应符合预期。http.Response 类型提供了各种方法来检查状态代码、标题和正文:
if resp.StatusCode != http.StatusOK {
// 断言失败,状态代码不正确
}
if resp.Header.Get("Content-Type") != "application/json" {
// 断言失败,内容类型不正确
}实用案例
假设我们有一个简单的 API,它接受一个 JSON 请求并返回用户列表。我们可以使用 Go 测试来验证该 API 的行为:
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestUsersAPI(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/api/v1/users", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
t.Errorf("Expected GET request, got %s", r.Method)
}
if r.Header.Get("Content-Type") != "application/json" {
t.Errorf("Expected application/json Content-Type, got %s", r.Header.Get("Content-Type"))
}
decoder := json.NewDecoder(r.Body)
var requestBody map[string]interface{}
if err := decoder.Decode(&requestBody); err != nil {
t.Errorf("Failed to decode request body: %v", err)
}
response := map[string]interface{}{"users": []string{"user1", "user2"}}
jsonResponse, _ := json.Marshal(response)
w.Header().Set("Content-Type", "application/json")
w.Write(jsonResponse)
})
server := httptest.NewServer(mux)
defer server.Close()
req, err := http.NewRequest("GET", server.URL+"/api/v1/users", strings.NewReader("{}"))
if err != nil {
t.Errorf("Failed to create request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
if err != nil {
t.Errorf("Failed to execute request: %v", err)
}
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status OK, got %d", resp.StatusCode)
}
if resp.Header.Get("Content-Type") != "application/json" {
t.Errorf("Expected application/json Content-Type, got %s", resp.Header.Get("Content-Type"))
}
decoder := json.NewDecoder(resp.Body)
var body map[string]interface{}
if err := decoder.Decode(&body); err != nil {
t.Errorf("Failed to decode response body: %v", err)
}
if len(body["users"].([]interface{})) != 2 {
t.Errorf("Expected 2 users, got %d", len(body["users"].([]interface{})))
}
}在测试中,我们模拟了服务器行为,然后向 API 发送一个 GET 请求。我们验证服务器是否正确处理请求并返回预期响应。
以上就是Golang 测试:如何测试与外部 API 的交互的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号