How to write unittest and fake response api in golang
This is our code that need to write unittest
func (s *emailServiceImpl) send(envelope *jarvis.EmailEnvelop, ctx context.Context) error { byteData, err := xml.Marshal(envelope) if err != nil { return err } client := apmhttp.WrapClient(&http.Client{Timeout: s.timeout*time.Minute,}) req, err := http.NewRequest("POST", s.url, bytes.NewBuffer(byteData)) if err != nil { return errors.Wrap(err, "Create new request failed") } req.SetBasicAuth(s.authentication.Username, s.authentication.Password) req.Header.Add("Content-Type", "text/xml;charset=UTF-8") req.Header.Add("Accept", "UTF-8") req.Header.Add("SOAPAction", "sendEmailWithBBC") resp, err := client.Do(req.WithContext(ctx)) if err != nil { logrus.Errorf("Send email fail %v", err) return errors.Wrap(err, "send mail error") } logrus.Infof("Send email success %v", resp) return nil}
Let's see, how to write unittest when we are having a small code
resp, err := client.Do(req.WithContext(ctx))
==> Thank for httptest package of Go
It is solved so easy now
Step 1: Create a server that it will receive request when client.Do
func serverMock(apiPath string) *httptest.Server { handler := http.NewServeMux() handler.HandleFunc(apiPath, sendMail) srv := httptest.NewServer(handler) return srv} func sendMail(w http.ResponseWriter, r *http.Request) { log.Info("response send mail succes") _, _ = w.Write([]byte("mock server responding")) }
Step 2: Start serverMock
func Test_emailServiceImpl_SendMail(t *testing.T) { api := "/notification/notificationService" srv := serverMock(api) defer srv.Close()
Step 3: Create your testcase with URL
{name: string("Happy case"), fields: fields{ url: srv.URL + api, timeout: 1, authentication: BasicAuthen{ Username: "fss", Password: "fss", }, }
http://www.inanzzz.com/index.php/post/fb0m/mocking-and-testing-http-clients-in-golang
https://medium.com/@xoen/go-testing-technique-testing-json-http-requests-76d9ce0e11f
https://blog.questionable.services/article/testing-http-handlers-go/
https://medium.com/@xoen/go-testing-technique-testing-json-http-requests-76d9ce0e11f
https://blog.questionable.services/article/testing-http-handlers-go/
Comments
Post a Comment