如果流程中有多个 GetItem(),如何模拟 AWS DynamoDB?

How to mock AWS DynamoDB if multiple GetItem() in flow?

eventHandler.go

func eventHandler(Id) error {
    eventDetails, err := GetEventStore(svc.Connection.DynamoDBClient, Id)
    if err != nil {
        log.Error("Error while reading Store", err)
        return err
    }
    if eventDetails.status == "completed" {
        config, err := GetConfig(svc.Connection.DynamoDBClient, Key)
        if err != nil {
            log.Error("Error while reading Config Store", err)
            return err
        }
        // process it
    }
  return nil
}

我们的大部分数据都存储在存储中,因此在为 eventHandler 编写单元测试时如何使用多个 GetItemOutput 模拟 DynamoDB?

eventHnadler_test.go

...
eventDetails := {
 //data
}
config := {
//data
}
        DB := client.DynamoDBClient{
            Client: mockDynamoDB{
                Output: dynamodb.GetItemOutput{
                    Item: eventDetails,
                },
                Error: tc.Error,
            },
        }
...

可以在 GO aws sdk v2 中模拟多个 get 调用吗?

因为 AWS dynamo DB 进行了重组所以

github.com/aws/aws-sdk-go-v2/service/dynamodb/dynamodbiface 不再存在你必须实现自己的接口才能有适当的发电机模拟

您的 Wrapper 围绕 aws 的实现应该与此类似

type Dynamodb struct {
    Client  DynamoAPI
}

type DynamoAPI interface {
        GetItem(ctx context.Context, params *dynamodb.GetItemInput, optFns ...func(*dynamodb.Options)) (*dynamodb.GetItemOutput, error)
        UpdateItem(ctx context.Context, params *dynamodb.UpdateItemInput, optFns ...func(*dynamodb.Options)) (*dynamodb.UpdateItemOutput, error)
        PutItem(ctx context.Context, params *dynamodb.PutItemInput, optFns ...func(*dynamodb.Options)) (*dynamodb.PutItemOutput, error)
        DeleteItem(ctx context.Context, params *dynamodb.DeleteItemInput, optFns ...func(*dynamodb.Options)) (*dynamodb.DeleteItemOutput, error)
        Query(ctx context.Context, params *dynamodb.QueryInput, optFns ...func(*dynamodb.Options)) (*dynamodb.QueryOutput, error)
        Scan(ctx context.Context, params *dynamodb.ScanInput, optFns ...func(*dynamodb.Options)) (*dynamodb.ScanOutput, error)
    }

这可能是你的模拟

type mockDynamodb struct {
    rbaws.DynamoAPI
    *dynamodb.Client
    clientError error
}

func (m mockDynamodb) GetItem(ctx context.Context, params *dynamodb.GetItemInput, optFns ...func(*dynamodb.Options)) (*dynamodb.GetItemOutput, error) {

    return &dynamodb.GetItemOutput{
        Item: map[string]types.AttributeValue{},
    }, m.clientError
}
func (m mockDynamodb) GetItem(ctx context.Context, params *dynamodb.GetItemInput, optFns ...func(*dynamodb.Options)) (*dynamodb.GetItemOutput, error) { 
 if (params.tablename == “eventDetails”) {     
  return m.eventDetailsItemOutput, m.clientError 
 } else {     
  return m.configItemOutput, m.clientError 
 } 
}

在测试文件中

DB := client.DynamoDBClient{
 Client: mockDynamoDB{
   eventDetailsItemOutput: dynamodb.GetItemOutput{
     Item: eventDetails,
   },
   configItemOutput: dynamodb.GetItemOutput{
     Item: eventDetails,
   },
   Error: tc.Error,
  },
}