[英]Validate request Body using github.com/jarcoal/httpmock
The function I am trying to test accepts data structs, forms a query_dsl
and then makes a /_search
call to elastic search with the formed query. 我试图测试的函数接受数据结构,形成一个
query_dsl
,然后用形成的查询对弹性搜索进行/_search
调用。 Hence I want to assert on the query_dsl
and url
which gets formed. 因此,我想断言在形成的
query_dsl
和url
上。
I am using github.com/jarcoal/httpmock
to mock net/http
requests in my unit tests. 我正在使用
github.com/jarcoal/httpmock
在我的单元测试中模拟net/http
请求。 As per the doc it exposes func GetCallCountInfo() map[string]int
to validate how many times a particular endpoint was hit. 根据文档,它公开
func GetCallCountInfo() map[string]int
以验证特定端点被击中的次数。 But I am also interested in knowing what was the request body when this call was made. 但是我也有兴趣知道在进行此调用时请求体是什么。
http.Client
is not exposed, hence can not override/mock that for testing. http.Client
未公开,因此无法覆盖/模拟测试。
If it is not possible using this package then is there any other library which can mock the network request and also gives hold of request body? 如果无法使用此软件包,那么是否有任何其他库可以模拟网络请求并且还提供请求正文?
Following @georgeok Suggestion, We can create a mock http server and capture the request body when request is made. 在@georgeok Suggestion之后,我们可以创建一个模拟http服务器并在请求时捕获请求体。 Following is the code snippet to create a server and store the request body.
以下是用于创建服务器和存储请求正文的代码段。
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
actualRequestBody, err = ioutil.ReadAll(req.Body)
check(err)
// Send mock response to be tested
_, err := rw.Write(bytes)
check(err)
}))
defer server.Close()
Now our request body is stored on actualRequestBody
variable, and we can assert on this for correctness. 现在我们的请求体存储在
actualRequestBody
变量中,我们可以断言它的正确性。
The only thing necessary to make sure this works is to make the call at host server.URL
. 确保其工作的唯一必要条件是在主机
server.URL
上进行调用。 As it spins up a server on the address mentioned at server.URL
. 因为它在
server.URL
上提到的地址上旋转服务器。 So if the call from your code is being made to different server this will not catch it. 因此,如果您的代码中的调用是针对不同的服务器进行的,那么这将无法捕获它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.