There are a lot of tools out there that do the full-fledged mock (for testing github.com/slack-go/slack
), but I still decide to provide an alternative because
- Instead of mocking slack client, I mock HTTP
- I only need a (very) few test cases, and I want something very lightweight.
So the steps are:
- mock the server
- create a service that will consume the api-client (
slack-go
) - write test
1. Mock The Server
I’m going to use PostMessage
as an example/guide for you to follow. The PostMessage
will use /chat.postMessage
endpoint. (feel free to lock up Slack’s doc or discover it from your error output)
Let’s define a serve mux and assign the endpoint to its handler.
handler := http.NewServeMux()
handler.HandleFunc("/chat.postMessage", handlePostMessage)httptest.NewServer(handler)// ...func handlePostMessage(w http.ResponseWriter, r *http.Request) {
const response = JSON_RESPONSE_FORMAT
w.WRITE([]BYTE(response))
}
where JSON_RESPONSE_FORMAT
is HERE, look for the Response section.