英文:
Golang how to mock aws sns in a lambda integration test or unit test
问题
我想在本地测试Lambda函数调用,而不使用AWS SNS服务。
func Handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error){
// ...执行一些逻辑和数据库操作
err := db.Create(something)
if err != nil {
msg := "something error."
target := "sns:arn"
// 发送SNS通知
sess := session.Must(session.NewSession())
svc := sns.New(sess, &cfg)
err = PublishNotification(svc, msg, target)
}
}
func PublishNotification(svc *sns.SNS, message string, target string) error {
params := sns.PublishInput{
Message: &message,
Subject: &subject,
TargetArn: &target,
}
req, _ := svc.PublishRequest(¶ms)
err := req.Send()
if err != nil {
return err
}
return nil
}
func main(){
lambda.Start(Handler)
}
现在一切都正常工作。我想对这个Lambda处理程序进行单元测试或集成测试。
func TestLabmdaWithSns(t *testing.T) {
tests := []struct {
request events.APIGatewayProxyRequest
}{
{request: events.APIGatewayProxyRequest{Body: "something"}},
}
for _, test := range tests {
response, err := Handler(test.request)
// 断言一些内容
}
}
在测试时,我不想发送SNS通知。
你可以如何模拟svc
或PublishNotification
函数,以便在本地测试时不发布消息到SNS呢?
英文:
I want to local test lambda function call and not use aws sns service.
func Handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error){
...do some logic and db opeations.
err := db.Create(something)
if err != nil {
msg := "something error."
target := "sns:arn"
// do sns notification
sess := session.Must(session.NewSession())
svc := sns.New(sess,&cfg)
err = PublishNotification(svc, msg, target)
}}
func PublishNotification(svc *sns.SNS, message string, target string) error {
params := sns.PublishInput{
Message: &message,
Subject: &subject,
TargetArn: &target,
}
req, _ := svc.PublishRequest(&params)
err := req.Send()
if err != nil {
return err
}
return nil
}
func main(){
lambda.Start(Handler)
}
Now Everything works fine. And I want to unit test or integration test this lambda handler.
func TestLabmdaWithSns(t *testing.T) {
tests := []struct {
request events.APIGatewayProxyRequest
}{
request: events.APIGatewayProxyRequest{Body:"something"}
}
for _, test := range tests {
response, err := Handler(test.request)
// assert something
}
}
And I dont want to send sns notification when testing.
<br>
How should I mock this svc or PublishNotification function to not publish message to sns when local testing ?
<br>
<br>
Thanks.
答案1
得分: 1
你应该在PublishNotification
中使用snsiface.SNSAPI
接口而不是*sns.SNS
。然后,你可以按照这里描述的方式,将snsiface.SNSAPI
的模拟实现注入到单元测试中:https://docs.aws.amazon.com/sdk-for-go/api/service/sns/snsiface/
英文:
You should use interface snsiface.SNSAPI instead of *sns.SNS in PublishNotification. Then you can inject mock implementation of snsiface.SNSAPI to the unit test as described here: https://docs.aws.amazon.com/sdk-for-go/api/service/sns/snsiface/
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论