单元测试Google的Go API客户端

问题描述 投票:1回答:2

我目前正在Go中编写一个使用Google的API go client的工作流程。我是Go的新手,我在单元测试客户服务时遇到了麻烦。以下是在Google Cloud Project中启用API的示例方法。

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是一个容纳客户端的简单结构。

type GCloudService struct {
   Client *http.Client
}

这是我尝试测试此方法。

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() {
  server.Close()
}

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

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

  testGcloudService := &GCloudService{
     Client: client,
  }

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

  mux.HandleFunc(path,
    func(w http.ResponseWriter, r *http.Request) {
        // test things...
    })

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

但是,当我运行此测试时,它仍会访问真正的Google端点而不是我的localhost服务器,因为EnableApi使用配置了API基本URL的服务管理服务。我如何重构这个来调用我的服务器而不是API?我希望尽可能避免嘲笑整个服务管理服务。

unit-testing go google-api client google-api-client
2个回答
0
投票

使您的服务管理服务中的基本URL可配置或可覆盖,如果这对您隐藏,那么您的代码不是为了测试方便而编写的,更改它,如果不可能,则向谁负责。如果这没有帮助,请深呼吸,并编写一个模拟服务,这通常不需要非常复杂


0
投票

我建议创建自己的界面,包装谷歌API客户端并提取您感兴趣的方法。

type MyWrapperClient interface {
   SomeMethodWithCorrectReturnType() 
} 

type myWrapperClient struct {
  *GCloudService.Client // or whatever 
}

然后在我运行的目录中:

mockery -name=MyWrapperClient目录内(安装嘲弄后)

然后你可以访问你的模拟版本。然后在对象创建中将mock替换为您的客户端 - 因为接口和mock具有相同的方法,它们是可互换的。然后,您可以测试是否使用特定参数调用方法 - 仅保留google api客户端代码。

有关嘲弄库的更多信息,请访问:https://github.com/vektra/mockery

这篇文章解决了同样的问题,它在解释如何模拟和抽象你的问题时非常棒。

https://medium.com/agrea-technogies/mocking-dependencies-in-go-bb9739fef008

© www.soinside.com 2019 - 2024. All rights reserved.