jarcoal/httpmock

MinTimes and MaxTimes responder invocations

ilya-hontarau opened this issue · 5 comments

As I can see, there is no way to set upper bound and lower bound of responder invocations, only Once() and exact amount with Times().
What do you think about adding these helper functions, like MinTimes() and MaxTimes()?

Hello, and what should reply httpmock before MinTimes() invocations are reached?

@maxatome I would expect the same behavior it has now for Times(), throwing panic

Hello, do you have a use case for this behavior?
As you will receive errors for the first MinTimes()-1 calls before receiving the first good response.

As you will receive errors for the first MinTimes()-1 calls before receiving the first good response.

What I thought, this check can be placed in a defer function, so it can assert in the end of the execution that min times isn't reached.

do you have a use case

I can see it useful, when testing logic with a undetermenistic behaivor, as example logic of pereodic pulling, retries.

As a Responder is a function (for historical reasons) it is not possible without doing dirty things to know how many times a Responder has been called.

But you can have a specific function to "track" a responder:

func Track(calls *int, r Responder) Responder {
	return func(req *http.Request) (*http.Response, error) {
		*calls++
		return r(req)
	}
}

this way you can know how many times it has been called, but explicitly:

var num int
r := Track(&num, httpmock.NewStringResponder(200, "OK))
httpmock.RegisterResponder("GET", "/foo", r)
httpmock.RegisterResponder("GET", "/bar", r)
// do your calls
fmt.Printf("The responder has been called %d times\n", num)

note that if you want to know how many times a URL has been mocked, you can simply use GetCallCountInfo.