2018-06-05 06:36
浏览 109

单元测试Google的Go API客户端

I am currently writing a workflow in Go that uses Google's API go client. I'm relatively new to Go and am having trouble unit testing the client's services. Here is an example method that enables an API in a Google Cloud Project.

func (gcloudService *GCloudService) EnableApi(projectId string, apiId string) error {
  service, err := servicemanagement.New(gcloudService.Client)
  if err != nil {
      return err

  requestBody := &servicemanagement.EnableServiceRequest{
      ConsumerId: consumerId(projectId),

  _, err = service.Services.Enable(apiId, requestBody).Do()
  if err != nil {
      return err

  return nil

GCloudService is a simple struct that holds a Client.

type GCloudService struct {
   Client *http.Client

This is my attempt at testing this method.

var (
  mux    *http.ServeMux
  client *http.Client
  server *httptest.Server

func setup() {
  // test server
  mux = http.NewServeMux()
  server = httptest.NewServer(mux)

  // client configured to use test server
  client = server.Client()

func teardown() {

func TestGCloudService_EnableApi(t *testing.T) {
  defer teardown()

  projectName := "test"
  apiId := "api"

  testGcloudService := &GCloudService{
     Client: client,

  path := fmt.Sprintf("/v1/services/{%s}:enable", apiId)

    func(w http.ResponseWriter, r *http.Request) {
        // test things...

  err := testGcloudService.EnableApi(projectName, apiId)
  if err != nil {
      t.Errorf("EnableApi returned error: %v", err)

However, when I run this test it still hits the real Google endpoint instead of my localhost server because EnableApi uses the servicemanagement service which is configured with the API's base URL. How do I refactor this to call my server instead of the API? I am hoping to avoid mocking the entire servicemanagement service if possible.

2条回答 默认 最新

相关推荐 更多相似问题