jarcoal/httpmock

No responder found when mocking with Cobra.Execute()

piyushsingariya opened this issue · 2 comments

Hi, I am trying to mock requests that are being made by some cobra commands in our CLI.
But I end up encountering this error
Get \"http://localhost:9081/api/user/performance/profiles?page_size=25&search=test\": no responder found

Here is the implementation:-

func TestPerfView(t *testing.T) {
	// setup current context
	utils.SetupContextEnv(t)

	// initialize mock server for handling requests
	utils.StartMockery(t)

	// create a test helper
	testContext := utils.NewTestHelper(t)

	// get current directory
	_, filename, _, ok := runtime.Caller(0)
	if !ok {
		t.Fatal("problems recovering caller information")
	}
	currDir := filepath.Dir(filename)
	fixturesDir := filepath.Join(currDir, "fixtures")

	// test scenrios for fetching data
	tests := []struct {
		Name             string
		Args             []string
		View             string
		ExpectedResponse string
		Fixture          string
		URL              string
		Token            string
		ExpectError      bool
	}{
		{
			Name:             "View Profiles",
			Args:             []string{"view", "test", "--token", filepath.Join(fixturesDir, "token.golden")},
			View:             "Profiles",
			ExpectedResponse: "view.profile.output.golden",
			Fixture:          "view.profile.api.response.golden",
			URL:              testContext.BaseURL + "/api/user/performance/profiles?search=test",
			Token:            filepath.Join(fixturesDir, "token.golden"),
			ExpectError:      false,
		},
	}

	// Run tests
	for _, tt := range tests {
		t.Run(tt.Name, func(t *testing.T) {
			// View api response from golden files
			apiResponse := utils.NewGoldenFile(t, tt.Fixture, fixturesDir).Load()

			// set token
			tokenPath = tt.Token

			// mock response
			httpmock.RegisterResponder("GET", tt.URL,
				httpmock.NewStringResponder(200, apiResponse))

			// Expected response
			testdataDir := filepath.Join(currDir, "testdata")
			golden := utils.NewGoldenFile(t, tt.ExpectedResponse, testdataDir)

			// Grab outputs from console.
			var buf bytes.Buffer
			log.SetOutput(&buf)
			utils.SetupLogrusFormatter()

			PerfCmd.SetArgs(tt.Args)
			PerfCmd.SetOutput(&buf)
			err := PerfCmd.Execute()
			if err != nil {
				// if we're supposed to get an error
				if tt.ExpectError {
					// write it in file
					if *update {
						golden.Write(err.Error())
					}
					expectedResponse := golden.Load()

					utils.Equals(t, expectedResponse, err)
					return
				} else {
					t.Error(err)
				}
			}

			// response being printed in console
			actualResponse := buf.String()

			// write it in file
			if *update {
				golden.Write(actualResponse)
			}
			expectedResponse := golden.Load()

			utils.Equals(t, expectedResponse, actualResponse)
		})
	}

	// stop mock server
	utils.StopMockery(t)
}

Hello,
If I understand well, you register a responder for /api/user/performance/profiles?search=test so not for /api/user/performance/profiles?page_size=25&search=test as expected. So it is normal no responder is found.
Try to register /api/user/performance/profiles instead, without any query param.

thanks, @maxatome for the assistance. I figured it out a bit later how exactly this thing works!