O
O
Oblomov952016-11-10 14:01:08
go
Oblomov95, 2016-11-10 14:01:08

How to write Unit tests for http requests (Go)?

Hello everyone, I'm learning to write unit tests, I can't quite understand how to write a test for http requests.
Let's say there is a function that takes an XML (yml) file from the network by url.

func (y *Yml) LoadXMLFromURL(url string) error {
  response, err := http.Get(url)
  if err != nil {
    return err
  }
  answer, err := ioutil.ReadAll(response.Body)
  if err != nil {
    return err
  }
  err = xml.Unmarshal(answer, y)
  return err
}

And I can’t quite understand how to use XML from the network in testing this function, that if the url with this XML is not available, the test will simply give an error.
I thought you could just write the XML to a variable and use it, am I right?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
al_gon, 2016-11-10
@Oblomov95

I think you are here https://github.com/jarcoal/httpmock

D
DmitriyTitov, 2019-12-25
@DmitriyTitov

In such cases, it is necessary to divide the complex function into parts. What I mean? Suppose your function requests data from the network or reads from disk and then processes it. In this case, writing a reliable autotest will not work. After all, the network and the disk are always uncertainty. Therefore, the function should be divided into two - data acquisition and data processing. In this case, data processing is easy to test by passing specially prepared data to the test. And the function of receiving data can already be tested either on the source emulator (database in memory, test server, special files, etc.) or even on a stub. And maybe even on real data sources - it all depends. At the same time, formally, you will have both unit tests and integration tests when using external components in tests.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question