3 回答

TA貢獻1921條經驗 獲得超9個贊
我認為您可以嘗試類似以下的操作(當然,您可能需要對此進行調整和實驗):
func TestTransform(t *testing.T) {
? ? mt := mtest.New(t, mtest.NewOptions().ClientType(mtest.Mock))
? ? defer mt.Close()
? ? mt.Run("find & transform", func(mt *mtest.T) {
? ? ? ? myollection = mt.Coll
? ? ? ? expected := myStructure{...}
? ? ? ? mt.AddMockResponses(mtest.CreateCursorResponse(1, "foo.bar", mtest.FirstBatch, bson.D{
? ? ? ? ? ? {"_id", expected.ID},
? ? ? ? ? ? {"field-1", expected.Field1},
? ? ? ? ? ? {"field-2", expected.Field2},
? ? ? ? }))
? ? ? ? response, err := myFindFunction(expected.ID)
? ? ? ? if err != nil {
? ? ? ? ? ? t.Error(err)
? ? ? ? }
? ? ? ? out := transform(response)
? ? ? ? if diff := deep.Equal(expected, out); diff != nil {
? ? ? ? ? ? t.Error(diff)
? ? ? ? }
? ? })
}
或者,您可以通過與 Docker 容器的集成測試以自動化的方式執行更真實的測試。

TA貢獻1891條經驗 獲得超3個贊
編寫可測試的最佳解決方案可能是將代碼提取到 DAO 或數據存儲庫。您將定義一個接口來返回您需要的內容。這樣,您就可以使用模擬版本進行測試。
// repository.go
type ISomeRepository interface {
? ? Get(string) (*SomeModel, error)
}
type SomeRepository struct { ... }
func (r *SomeRepository) Get(id string) (*SomeModel, error) {
? ? // Handling a real repository access and returning your Object
}
當你需要模擬它時,只需創建一個 Mock-Struct 并實現接口:
// repository_test.go
type SomeMockRepository struct { ... }
func (r *SomeRepository) Get(id string) (*SomeModel, error) {
? ? return &SomeModel{...}, nil
}
func TestSomething() {
? ? // You can use your mock as ISomeRepository
? ? var repo *ISomeRepository
? ? repo = &SomeMockRepository{}
? ? someModel, err := repo.Get("123")
}
這最好與某種依賴注入一起使用,因此將此存儲庫作為 ISomeRepository 傳遞到函數中。

TA貢獻1804條經驗 獲得超8個贊
使用 Monkey 庫來掛鉤 mongo 驅動程序中的任何函數。
例如:
func insert(collection *mongo.Collection) (int, error) {
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
u := User{
Name: "kevin",
Age: 20,
}
res, err := collection.InsertOne(ctx, u)
if err != nil {
log.Printf("error: %v", err)
return 0, err
}
id := res.InsertedID.(int)
return id, nil
}
func TestInsert(t *testing.T) {
var c *mongo.Collection
var guard *monkey.PatchGuard
guard = monkey.PatchInstanceMethod(reflect.TypeOf(c), "InsertOne",
func(c *mongo.Collection, ctx context.Context, document interface{}, opts ...*options.InsertOneOptions) (*mongo.InsertOneResult, error) {
guard.Unpatch()
defer guard.Restore()
log.Printf("record: %+v, collection: %s, database: %s", document, c.Name(), c.Database().Name())
res := &mongo.InsertOneResult{
InsertedID: 100,
}
return res, nil
})
collection := client.Database("db").Collection("person")
id, err := insert(collection)
require.NoError(t, err)
assert.Equal(t, id, 100)
}
- 3 回答
- 0 關注
- 241 瀏覽
添加回答
舉報