Test Slack in GO

Jim Kang
2 min readOct 19, 2020

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

  1. Instead of mocking slack client, I mock HTTP
  2. I only need a (very) few test cases, and I want something very lightweight.

So the steps are:

  1. mock the server
  2. create a service that will consume the api-client ( slack-go )
  3. 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.

server.go

--

--

Jim Kang

love writing bit sized programming memo, acoustic guitarist, proud daddy of 5 and great listener (to my kids)