0

I want to test LoadPage and GetData function. While testing LoadPage, I want to mock GetData function, how to do that? Don't want to use something like this type PageGetter func(url string) string and pass mock func as parameter

package main

import (
    "net/http"
    "os"
    "fmt"
    "io/ioutil"
)

func GetData(url string) (*http.Response,error){
    return http.Get(url)
}

func LoadPage(url string) {

    resp,err := GetData(url)
    if err != nil {
        os.Exit(0)
    }
    data,err :=ioutil.ReadAll(resp.Body)
    fmt.Println(string(data))
}

func main()  {
    var url string
    fmt.Scanf("%s", &url)
    LoadPage(url)
}
  • Possible duplicate of [Mock functions in Go](https://stackoverflow.com/questions/19167970/mock-functions-in-go) – Dharma Saputra Nov 27 '17 at 10:36
  • @DharmaSaputra, I already look at that answer but want a different possible approach/solution – Vikram Singh Choudhary Nov 27 '17 at 10:47
  • I think you are looking for https://golang.org/pkg/net/http/httptest/. A discussion on SO [here](https://stackoverflow.com/questions/16154999/how-to-test-http-calls-in-go-using-httptest). – k1m190r Nov 27 '17 at 11:04
  • Why do you not want to change the interface of the function? I ask because that will change how you can implement it. – Hein Oldewage Nov 29 '17 at 08:42

0 Answers0