Home > Back-end >  How do I guarantee that the request happened correctly when mocking an API?
How do I guarantee that the request happened correctly when mocking an API?

Time:11-25

Let's say I'm testing a feature that calls a web service, and that service is mocked with httptest.NewServer

func TestSomeFeature(t *testing.T) {
    server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(200)
    }))

    SomeFeature(server.URL, "foo")
}

func SomeFeature(host, a string) {
    if a == "foo" {
        http.Get(fmt.Sprintf("%v/foo", host))
    }
    if a == "bar" {
        http.Get(fmt.Sprintf("%v/bar", host))
    }
}

How do I assert that the server was called with the right url /foo and fail the test if it was called with the wrong url or not called at all?

CodePudding user response:

You can do it like this:

func TestSomeFeature(t *testing.T) {
    called := false
    server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // assert that strings.Contains(r.RequestURI, "/foo") is true
        called = true
        w.WriteHeader(200)
    }))

    SomeFeature(server.URL, "foo")
    // assert that called is true
}
  • Related