aldikhan13

CUSTOM HTTP REQUEST FOR TESTING IN GO

Apr 1st, 2021 (edited)
374
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.31 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "bytes"
  5.     "encoding/binary"
  6.     "net/http"
  7.     "net/http/httptest"
  8.     "github.com/sirupsen/logrus"
  9.     "net/http"
  10.     "testing"
  11.     "github.com/stretchr/testify/assert"
  12. )
  13.  
  14. // helper.go
  15. func JSONStrigify(payload string) []byte {
  16.     jsonData := []byte(payload)
  17.     return jsonData
  18. }
  19.  
  20. // request.go
  21. func HttpTestRequest(handler http.Handler, method, url string, payload []byte) *httptest.ResponseRecorder {
  22.  
  23.     request := make(chan *http.Request)
  24.     errors := make(chan error)
  25.  
  26.     if binary.Size(payload) > 0 {
  27.         req, err := http.NewRequest(method, url, bytes.NewBuffer(payload))
  28.         go func() {
  29.             request <- req
  30.             errors <- err
  31.         }()
  32.     } else {
  33.         req, err := http.NewRequest(method, url, nil)
  34.         go func() {
  35.             request <- req
  36.             errors <- err
  37.         }()
  38.     }
  39.  
  40.     if <-errors != nil {
  41.         logrus.Error(<-errors)
  42.     }
  43.  
  44.     rr := httptest.NewRecorder()
  45.     handler.ServeHTTP(rr, <-request)
  46.  
  47.     return rr
  48. }
  49.  
  50. // main_test.go
  51. func TestCreateAccount(t *testing.T) {
  52.  
  53.     router := setupRouter()
  54.  
  55.     res := helper.HttpTestRequest(router, "POST", "/account", helper.JSONStrigify(`{
  56.         "name":"xyz",
  57.         "ic_type":"pqr",
  58.         "ic_number_identity":"xyz@pqr.com",
  59.         "account_number":"1234567890",
  60.         "account_name":"1234567890",
  61.         "bank_name":"1234567890",
  62.         "type":"1234567890"
  63.     }`))
  64.  
  65.     assert.Equal(t, http.StatusOK, res.Code)
  66. }
Add Comment
Please, Sign In to add comment