最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

amazon web services - How do I properly mock a function? - Stack Overflow

programmeradmin1浏览0评论

I developed a AWS Lambda function in Go. Now I'm trying to unit test it.

In my main.go I have this variable:

var (
    core *Core
)

Core is a struct that holds SecretIDs, a httpClient and so on.

I also have a core.go, where I defined functions that do request (AWS) services.

Now, in my main.go Go code there is a main(), init() and a HandleRequest(). I want to unit test the HandleRequest() function, which holds another function from core.go, where another service is requested.

But whatever I do, once I call the HandleRequest() in my unit test function, the lambda code is trying to fetch secrets, which is happening in my init() function.

This is my test code so far:

type MockCore struct {
    *Core
}

func (m *MockCore) FetchDetails(vorname, nachname, strasse, plz, ort string) ([]int, error) {
    if vorname == "error" {
        return nil, errors.New("mocked error")
    }
    return []int{12345, 67890}, nil
}

func TestHandleRequest(t *testing.T) {

    originalCore := core
    mockCore := &MockCore{
        Core: &Core{
            Logger: zap.NewNop(),

        },
    }
    core = mockCore.Core
    defer func() { core = originalCore }()

    t.Run("Successful Fetch", func(t *testing.T) {
        req := events.APIGatewayProxyRequest{
            QueryStringParameters: map[string]string{
                "vorname":  "Test",
                "nachname": "Test",
                "strasse":  "Test Street",
                "plz":      "12345",
                "ort":      "Test",
            },
        }

        resp, err := HandleRequest(req)

But the test is running the init() and I receive this error: "msg":"unable to read secret from secret manager"

I just want to test one method and don't want to establish any connection to AWS. Can anyone help?

发布评论

评论列表(0)

  1. 暂无评论