登录
首页 >  Golang >  Go问答

使用 Golang 中的 httptest 拦截和模拟 HTTP 响应的实现方法

来源:stackoverflow

时间:2024-02-15 15:00:23 343浏览 收藏

一分耕耘,一分收获!既然打开了这篇文章《使用 Golang 中的 httptest 拦截和模拟 HTTP 响应的实现方法》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!

问题内容

我研究了可用于 golang 中模拟测试的各种不同工具,但我正在尝试使用 httptest 来完成此任务。特别是,我有一个这样的函数:

type contact struct {
  username string
  number int
}

func getResponse(c contact) string {
  url := fmt.Sprintf("https://mywebsite/%s", c.username)
  req, err := http.NewRequest(http.MethodGet, url, nil)
  // error checking
 
  resp, err := http.DefaultClient.Do(req)
  // error checking
  
  return response
}

我读过的很多文档似乎都需要创建客户端接口或自定义传输。有没有办法在不更改此主代码的情况下模拟测试文件中的响应?我想将我的客户端、响应和所有相关详细信息保留在 getresponse 函数中。我可能有错误的想法,但我正在尝试找到一种方法来拦截 http.defaultclient.do(req) 调用并返回自定义响应,这可能吗?


正确答案


我读过似乎需要创建一个客户端界面

根本不改变这个主要代码

保持代码干净是一个很好的做法,您最终会习惯它,可测试的代码更干净,更干净的代码更可测试,所以不必担心更改您的代码(使用接口),这样它就可以接受模拟对象。

最简单形式的代码可以是这样的:

package main

import (
    "fmt"
    "net/http"
)

type contact struct {
    username string
    number   int
}

type client interface {
    do(req *http.request) (*http.response, error)
}

func main() {
    getresponse(http.defaultclient, contact{})
}

func getresponse(client client, c contact) string {
  url := fmt.sprintf("https://mywebsite/%s", c.username)
  req, _ := http.newrequest(http.methodget, url, nil)
  // error checking

  resp, _ := http.defaultclient.do(req)
  // error checking and response processing

  return response
}

你的测试可以是这样的:

package main

import (
    "net/http"
    "testing"
)

type mockclient struct {
}

// do function will cause mockclient to implement the client interface
func (tc mockclient) do(req *http.request) (*http.response, error) {
    return &http.response{}, nil
}

func testgetresponse(t *testing.t) {
    client := new(mockclient)
    getresponse(client, contact{})
}

但是如果您更喜欢使用 httptest:

package main

import (
    "fmt"
    "io"
    "net/http"
    "net/http/httptest"
)

type contact struct {
    username string
    number   int
}

func main() {
    fmt.Println(getResponse(contact{}))
}

func getResponse(c contact) string {
    // Make a test server
    ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "your response")
    }))

    defer ts.Close()

    // You should still set your base url
    base_url := ts.URL

    url := fmt.Sprintf("%s/%s", base_url, c.username)
    req, _ := http.NewRequest(http.MethodGet, url, nil)

    // Use ts.Client() instead of http.DefaultClient in your tests.
    resp, _ := ts.Client().Do(req)

    // Processing the response
    response, _ := io.ReadAll(resp.Body)
    resp.Body.Close()

    return string(response)
}

好了,本文到此结束,带大家了解了《使用 Golang 中的 httptest 拦截和模拟 HTTP 响应的实现方法》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>