I'm trying to get a 100% code coverage on this simple http handler file.
The file writes the default response headers if successful and then returns 200 with "Pong" which I've tested below. However, there is also a possibility that writing the default headers will generate an error in which case a 500 response with Internal Error body is expected.
I'm struggling to figure out how to trigger the 500 response case in a test. The case would fail if for some reason the writeDefaultHeaders function call's 2nd parameter was changed to "html" for example as html is not a supported response content type in my service.
What is the idiomatic way to mock this call / hit this error branch in the code?
Thanks.
ping_handler_test.go
package main
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestPingHandler(t *testing.T) {
req, _ := http.NewRequest("GET", "/ping", nil)
w := httptest.NewRecorder()
PingHandler(w, req)
if w.Code != http.StatusOK {
t.Errorf("Ping Handler Status Code is NOT 200; got %v", w.Code)
}
if w.Body.String() != "Pong" {
t.Errorf("Ping Handler Response Body is NOT Pong; got %v", w.Body.String())
}
}
func BenchmarkPingHandler(b *testing.B) {
for i := 0; i < b.N; i++ {
req, _ := http.NewRequest("GET", "/ping", nil)
w := httptest.NewRecorder()
PingHandler(w, req)
}
}
ping_handler.go
package main
import (
"fmt"
"net/http"
)
func PingHandler(w http.ResponseWriter, r *http.Request) {
err := writeDefaultHeaders(w, "text")
if err != nil {
handleException(w, err)
return
}
fmt.Fprintf(w, "Pong")
}
Aucun commentaire:
Enregistrer un commentaire