测试Go(Golang)API传出请求而不实际触及第三方API

时间:2016-07-12 21:59:51

标签: api testing go

我正在开发一个Go API,它在内部后端和几个第三方API之间进行转换。我试图了解如何在不实际使用外部API的情况下测试其功能。

例如,这是一个处理传入请求以制作新歌曲的服务器,并将请求发送给第三方API:

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(request)处理程序,以便隔离incomingRequestToOutgoingRequest中发生的事情吗?

我们赞赏任何正确方向的帮助/建议/要点。

我可以在这里测试package main import ( "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) } }

java.io.IOException: mark/reset not supported
    at java.util.zip.InflaterInputStream.reset(Unknown Source)
    at java.io.FilterInputStream.reset(Unknown Source)
    at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(Unknown Source)
    at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
    at com.neet.Audio.JukeBox.load(JukeBox.java:26)
    at com.neet.GameState.IntroState.<init>(IntroState.java:28)
    at com.neet.GameState.GameStateManager.loadState(GameStateManager.java:48)
    at com.neet.GameState.GameStateManager.setState(GameStateManager.java:72)
    at com.neet.GameState.GameStateManager.<init>(GameStateManager.java:31)
    at com.neet.Main.GamePanel.init(GamePanel.java:70)
    at com.neet.Main.GamePanel.run(GamePanel.java:75)
    at java.lang.Thread.run(Unknown Source)

1 个答案:

答案 0 :(得分:8)

您可以像这样使用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