例如,这是一个处理传入请求以制作新歌曲的服务器,并将请求发送给第三方API:
package mainimport ( "bytes" "enCoding/Json" "fmt" "net/http")var ThirdPartyAPI = "http://www.coolsongssite.API"type IncomingRequest struct { username string `Json:"username"` password string `Json:"password"` songs []IncomingSong `Json:"songs"`}type OutgoingRequest struct { username string `Json:"username"` password string `Json:"password"` songs []OutgoingSong `Json:"songs"`}type IncomingSong struct { artist string `Json:"artist"` album string `Json:"album"` Title string `Json:"Title"`}type OutgoingSong struct { musician string `Json:"musician"` record string `Json:"record"` name string `Json:"name"`}func main() { http.HandleFunc("/songs/create",createSong) http.ListenAndServe(":8080",nil)}func createSong(rw http.ResponseWriter,req *http.Request) { decoder := Json.NewDecoder(req.Body) var incomingRequest IncomingRequest decoder.Decode(&incomingRequest) outgoingRequest := incomingRequestToOutgoingRequest(incomingRequest) r,_ := Json.Marshal(outgoingRequest) request,_ := http.NewRequest("POST",ThirdPartyAPI,bytes.NewBuffer(r)) request.header.Set("Content-Type","application/Json") clIEnt := http.ClIEnt{} response,_ := clIEnt.Do(request) fmt.Fprintln(rw,response)}func incomingRequestToOutgoingRequest(inc IncomingRequest) OutgoingRequest { outgoingRequest := OutgoingRequest{ username: inc.username,password: inc.password,} for _,s := range inc.songs { outgoingRequest.songs = append( outgoingRequest.songs,OutgoingSong{ musician: s.artist,record: s.album,name: s.Title,},) } return outgoingRequest}
所以我可能会点击在localhost:8080上运行的应用程序:
curl -X POST http://localhost:8080/songs/new --data \'{"username": "<my-username>","password": "<my-password>","songs": \["artist": "<song-artist>","Title": "<song-Title>","album": "<song-album>"]}'
我的问题是:
如何编写测试来测试发出的请求(在本例中为http://www.coolsongssite.API)是否正确,而不实际发送?
我应该重写createSong处理程序,以便我可以隔离clIEnt.Do(请求)中发生的事情吗?
任何有关正确方向的帮助/建议/要点都会受到赞赏.
在这里我可以像这样测试incomingRequestToOutgoingRequest:
package mainimport ( "testing")func TestincomingRequestToOutgoingRequest(t *testing.T) { incomingRequest := IncomingRequest{ username: "myuser",password: "mypassword",} var songs []IncomingSong songs = append( songs,IncomingSong{ artist: "White Rabbits",album: "Milk Famous",Title: "I'm Not Me",) outgoingRequest := incomingRequestToOutgoingRequest(incomingRequest) if outgoingRequest.songs[0].musician != "White Rabbits" { t.Error("Expected musican name to be 'White Rabbits'. Got: ",outgoingRequest.songs[0].musician) }}您可以像这样使用net / http / httptest.NewServer:
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter,r *http.Request) { w.Write([]byte(`desired response here`))}))defer ts.Close()ThirdPartyAPI = ts.URL...your test here总结
以上是内存溢出为你收集整理的测试Go(Golang)API传出请求而不实际触及第三方API全部内容,希望文章能够帮你解决测试Go(Golang)API传出请求而不实际触及第三方API所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)