A
A
Alexander Melentyev2019-12-22 13:36:13
go
Alexander Melentyev, 2019-12-22 13:36:13

How to cover with tests _, err = w.Write(res)?

Good afternoon!
There is a function:

func Respond(w http.ResponseWriter, data map[string]interface{}) {
  w.Header().Set("Access-Control-Allow-Origin", "*")
  w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
  w.Header().Set("Access-Control-Allow-Headers", "Accept, Authorization, Content-Type, X-CSRF-Token")
  w.Header().Set("Content-Type", "application/json")
  res, err := json.Marshal(data)
  if err != nil {
    log.Printf("marshal error: %v", err)
  }
  _, err = w.Write(res)
  if err != nil {
    log.Printf("write error: %v", err)
  }
}

There is also a test, but it only covers 90%
func TestRespond(t *testing.T) {
  w := httptest.NewRecorder()
  w.WriteHeader(500)
  x := map[string]interface{}{
    "foo": make(chan int),
  }
  Respond(w, x)
}

Orient how to cover the next part of the code with tests?
_, err = w.Write(res)
if err != nil {
  log.Printf("write error: %v", err)
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
rustler2000, 2019-12-23
@asmelentyev

Is this really such a test or just the checks after Respond(w, x) are cut out?
Obviously, you will have to make your own ResponseRecorder which will give an error on Write.
Like https://play.golang.org/p/eqUpcDqPrKN

U
uvelichitel, 2019-12-22
@uvelichitel

//In func TestRespond(t *testing.T)
resp := w.Result() //Give you *http.Responce
body, _ := ioutil.ReadAll(resp.Body) //Responce body written in *bytes.Buffer You can read it
//Check it
if resp.StatusCode ...........{
    t.Errorf(........)
}
if body ............ {
    t.Errorf(........)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question