2018-09-26 20:51
浏览 70

在Go中测试Lambda处理程序时如何模拟AWS Lambda上下文?

I have an S3-triggered AWS Lambda written in Go. I've been able to successfully test all of the ancillary code, however, I'm stuck trying to test the lambda handler.

Here's the signature of my handler:

func HandleRequest(ctx context.Context, s3Event events.S3Event)

Here's the test code:

package main

import (


func TestHandleRequest(t *testing.T) {
  // 1. read JSON from file
  inputJSON, err := readJSONFromFile("./testdata/s3-event.json")
  if err != nil {
    t.Errorf("could not open test file. details: %v", err)

  // 2. de-serialize into Go object
  var inputEvent events.S3Event
  if err := json.Unmarshal(inputJSON, &inputEvent); err != nil {
    t.Errorf("could not unmarshal event. details: %v", err)

  // 3. How can I mock the context.Context?

  assert.NoError(t, HandleRequest(context.Context, inputEvent))

I have no clue how I should mock the context.Context. I couldn't find any examples online either.

Anyone know? Does my code look idiomatic for testing an S3-triggered, Go Lambda?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dtcrw26206 2018-09-27 02:04

    ‘context.Context’ is designed to be an immutable value (even though it is literally an interface). So I wouldn’t be concerned with mocking it.

    There are two ways to create empty contexts (‘context.Background()’ and ‘context.TODO()’). I would start with those. If you want to set something on the context, check out documentation on the context package.

    点赞 打赏 评论
  • drexlz0623 2018-09-26 23:35

    Will context.TODO satisfy your needs?


    点赞 打赏 评论

相关推荐 更多相似问题