1 回答
TA贡献2080条经验 获得超4个赞
首先,使你的处理程序成为一个不起眼的对象,这样我们就可以“跳过”测试它:
func handler(ctx context.Context, req events.APIGatewayProxyRequest)
(events.APIGatewayProxyResponse, error) {
dynamoWrapper := &RealDynamoWrapper{}
proxyController := &ProxyController{DynamoWrapper: dynamoWrapper}
return proxyController.proxy(ctx, req)
这个想法是使处理程序函数变得谦卑,方法是让它将所有复杂性委托给 .proxyController
现在,让我们考虑要测试的,我们需要先定义它:ProxyController
type ProxyController struct {
dynamoWrapper DynamoWrapper
}
func(controller *ProxyController) Proxy(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
// this is where your implementation lives that you need to mock stuff for
// We are mocking this line from your question
svc := controller.dynamoWrapper.NewFromConfig(...)
// do other stuff and then return something
return events.APIGatewayProxyResponse{}, nil
}
你可以看到我将依赖于一个包装版本的dynamo,它看起来像这样:
type DynamoWrapper interface {
NewFromConfig(cfg aws.Config, optFns ...func(*Options)) *Client
}
现在,此包装器的真正实现,上面引用的那个将像对 sdk 执行操作一样进行调用。但是,对于我们的测试,我们想要一个模拟实现:RealDynamoWrapper
type mockDynamoWrapper struct {
NewFromConfigFunc func(aws.Config, ...func(*Options)) *Client
}
func(dynamoWrapper *mockDynamoWrapper) NewFromConfig(cfg aws.Config, optFns ...func(*Options)) *Client {
return dynamoWrapper.NewFromConfigFunc(cfg, optFns...)
}
最后,在测试中,您现在可以模拟发电机调用:
func TestProxyController(t *testing.T) {
// given
dynamoWrapper := &mockDynamoWrapper{}
proxyController := &ProxyController{DynamoWrapper: mockDynamoWrapper}
request := events.APIGatewayProxyRequest{}
dynamoWrapper.NewFromConfigFunc = func(aws.Config, ...func(*Options)) *Client {
// setup your mock function to do whatever you want
}
// when
proxyController.proxy(context.Background, request)
// then do your asserts
}
- 1 回答
- 0 关注
- 81 浏览
添加回答
举报