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",
   },
}




Comments

Popular posts from this blog

Fixing the DeepSpeed Import Error While Fine-Tuning the Qwen Model

Amazon Linux 2023 - User data configuration for launch templates to connect to the EKS cluster

How to create ISM policy and rotate logs in opensearch