i have a handler function which is called CreateObject. This function wraps at the same time a POST request to an external API which i dont control. If I want to unit test it, the problem I face is that I can't be posting new objects to the external service every time I run the test. So I would like to know if there is a way to mock this with Go or any workaround.
Many thanks.
package main
func main() {
router := mux.NewRouter()
router.HandleFunc("/groups", services.CreateObject).Methods("POST")
c := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowCredentials: true,
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"},
AllowedHeaders: []string{"*"},
ExposedHeaders: []string{"*"},
})
handler := c.Handler(router)
http.ListenAndServe(":3000", handler)
package objects
func CreateObject(w http.ResponseWriter, r *http.Request) {
var newobject Object
_ = json.NewDecoder(r.Body).Decode(&newobject )
//Do things
jsonStr, err := json.Marshal(newobject)
if err != nil {
fmt.Println(err)
return
}
req, err := http.NewRequest("POST", ExternalURL+"/object", bytes.NewBuffer(jsonStr))
if err != nil {
fmt.Println(err)
return
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
if resp.StatusCode < 200 || resp.StatusCode > 299 {
w.WriteHeader(resp.StatusCode)
w.Header().Set("Content-Type", "application/json")
w.Write(body)
} else {
w.WriteHeader(201)
}
}