Go 单元测试之HTTP请求与API测试
    		       		warning:
    		            这篇文章距离上次修改已过446天,其中的内容可能已经有所变动。
    		        
        		                
                
package main
 
import (
    "net/http"
    "net/http/httptest"
    "testing"
 
    "github.com/stretchr/testify/assert"
)
 
// 模拟的HTTP处理函数
func mockHandler(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    w.Header().Set("Content-Type", "application/json")
    _, _ = w.Write([]byte(`{"message": "Hello, World!"}`))
}
 
// 测试用例函数
func TestMockAPI(t *testing.T) {
    // 创建一个模拟的服务器,运行mockHandler
    server := httptest.NewServer(http.HandlerFunc(mockHandler))
    defer server.Close()
 
    // 发送HTTP GET请求到模拟的服务器
    resp, err := http.Get(server.URL)
    assert.Nil(t, err)
    defer resp.Body.Close()
 
    // 验证响应状态码
    assert.Equal(t, http.StatusOK, resp.StatusCode)
 
    // 读取响应体
    body, err := io.ReadAll(resp.Body)
    assert.Nil(t, err)
 
    // 验证响应体内容
    expected := `{"message": "Hello, World!"}`
    assert.Equal(t, expected, string(body))
}这段代码首先定义了一个模拟的HTTP处理函数mockHandler,然后创建了一个模拟的HTTP服务器server来运行这个处理函数。在测试用例TestMockAPI中,我们向模拟服务器发送一个HTTP GET请求,并验证返回的状态码和响应体是否符合预期。这是一个很好的实践,展示了如何使用Go语言进行HTTP请求和API的单元测试。
评论已关闭