我有一個服務來獲取資料庫資料并從第三方 api 獲取其他資料。
像這樣:
type Service interface {
GetDataFromDB(params apiParams, thirdClient ApiCient)
}
type Repository interface {
GetDataFromDB(orm *gorm.DB)
}
type DataService struct {
repo Repository
}
func (s *DataService) GetDataFromDB(params apiParams, thirdClient ApiClient) []interface{} {
var result []interface{}
dataFromDb := s.repo.GetDataFromDB()
dataFromAPI := thirdClient.Do(url)
result = append(result, dataFromDb)
result = append(result, dataFromAPI)
return result
}
func getData(c *gin.Context) {
//already implement interface
repo := NewRepository(orm)
srv := NewService(repo)
thirdPartyClient := NewApiClient()
params := ¶ms{Id:1,Name:"hello world"}
res := srv.GetDataFromDB(params, thirdPartyClient)
c.JSON(200,res)
}
func TestGetData(t *testing.T) {
w := httptest.NewRecorder()
request := http.NewRequest(http.MethodGet, "/v1/get_data", nil)
route.ServeHTTP(w, request)
}
第三方 api 客戶端將回傳隨機資料。
在這種情況下,我該怎么辦?
如果我想模擬客戶端以獲得穩定的資料進行測驗,如何在集成測驗中偽造它?
uj5u.com熱心網友回復:
我假設“集成測驗”意味著您將運行整個應用程式,然后測驗正在運行的實體及其依賴項(在您的情況下是資料庫和第三方服務)。我假設您不是指單元測驗。
對于集成測驗,您有幾個選擇。就我而言,通常我會集成測驗,包括第三方客戶端連接到的任何內容(沒有模擬),因為我想測驗我的服務與第三方服務的集成。或者,如果這是不可能的,我可能會撰寫一個與第三方服務具有相同公共介面的簡單存根應用程式,并在本地主機(或某處)上運行它,以便我的應用程式在測驗期間連接到。
如果您不想或不能執行其中任何一項操作并希望在 Go 應用程式中存根外部依賴項,則可以為第三方客戶端撰寫一個介面,并在運行集成測驗時提供該介面的存根實作(在您的應用程式上使用一個標志來告訴它以“存根”模式或類似的方式運行)。
下面是一個示例,說明這可能是什么樣子。這是您發布的源代碼檔案 - 但使用介面獲取第三方資料:
type Service interface {
GetDataFromDB(params apiParams, thirdClient ApiCient)
}
type Repository interface {
GetDataFromDB(orm *gorm.DB)
}
type ThirdPartyDoer interface {
Do(url string) interface{}
}
type DataService struct {
repo Repository
thirdParty ThirdPartyDoer
}
func (s *DataService) GetDataFromDB(params apiParams, thirdClient ApiClient) []interface{} {
var result []interface{}
dataFromDb := s.repo.GetDataFromDB()
dataFromAPI := s.thirdParty.Do(url)
result = append(result, dataFromDb)
result = append(result, dataFromAPI)
return result
}
然后您可以撰寫存根實作ThirdPartyDoer并在測驗時使用它。在 Production 中運行時,您可以使用真正的第三方客戶端作為ThirdPartyDoer的實作:
type thirdPartyDoerStub struct {}
func (s *thirdPartyDoerStub) Do(url string) interface{} {
return "some static test data"
}
// ...
// Test setup:
integrationTestDataService := &DataService{repo: realRepository, thirdParty: &thirdPartyDoerStub{}}
// Production setup:
integrationTestDataService := &DataService{repo: realRepository, thirdParty: realThirdParty}
啟動應用程式時,您需要有一個標志來在“測驗設定”和“生產設定”之間進行選擇。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/391804.html
