lundi 31 juillet 2017

Returning different values from a stubbed out service or function?

I have created a function that will query a service for a true or false status. This function will sleep and retry until the service returns true.

func main() {
    fmt.Println("Hello, playground")

    for {
        query, err := getQueryValue()
        if err != nil {
            return "error"
        }
        // assume new_args gets a value to be used. 
        new_args := someLogicWithLoop()
        if parseMyQuery(query, new_args) {
            return "success"
        }
        time.Sleep(delayTime)
    }
}

What is the best way to test this? I feel like I should have a stubbed service that will return false for the first time and then return true.

I was thinking something like this -

type fakeService struct {
    //some interface
    err error
    want bool
}

func (f *fakeService) doSmth() int {
    if f.want {
        return 1
    }
    return 0
}

func main() {
    a := &fakeService{want: true}   
    fmt.Println(a.doSmth())
}

However, it doesn't seem to be very flexible. What are some alternative / cleaner ways to achieve the above?

Aucun commentaire:

Enregistrer un commentaire