如何测试需要令牌才能调用数据服务的处理程序?

huangapple go评论78阅读模式
英文:

How do I test my handler which require tokens to call data services

问题

这是在处理程序中编写的代码,用于获取调用数据服务所需的令牌。

m2m, err := h.getM2MToken(ctx)

if err != nil {
    return lc.SetResponse(&events.APIGatewayV2HTTPResponse{
        StatusCode: http.StatusInternalServerError,
        Body:       "Internal Server Error (m2m)",
    })
}

// 获取承载令牌
userToken, err := h.getBearer(req.Headers)
if err != nil {
    xray.AddError(ctx, err)
    return lc.SetResponse(&events.APIGatewayV2HTTPResponse{
        StatusCode: http.StatusInternalServerError,
        Body:       "Internal Server Error (bearer)",
    })
}

请注意,这只是代码的一部分,用于获取令牌并处理可能的错误。

英文:

This is the code written in the handler, which gets the token required to call the data service.

m2m, err := h.getM2MToken(ctx)

if err != nil {
	return lc.SetResponse(&events.APIGatewayV2HTTPResponse{
		StatusCode: http.StatusInternalServerError,
		Body:       "Internal Server Error (m2m)",
	})
}

//Get the bearer token
userToken, err := h.getBearer(req.Headers)
if err != nil {
	xray.AddError(ctx, err)
	return lc.SetResponse(&events.APIGatewayV2HTTPResponse{
		StatusCode: http.StatusInternalServerError,
		Body:       "Internal Server Error (bearer)",
	})
}

答案1

得分: 1

我的建议是首先尝试将您发送给方法的输入进行抽象化处理。

例如,不要这样写:

userToken, err := h.getBearer(req.Headers)

而是可以指定接口,如下所示:

type userTokenInput struct {}
uti := userTokenInput{} 
userToken, err := h.getBearer(uti)

上述方法可以帮助您对输入进行控制,从而使测试更容易进行。

对于网络调用,尝试使用一些模拟的HTTP客户端,该客户端可以返回预期的数据。您可以参考以下链接了解如何模拟HTTP客户端:https://www.thegreatcodeadventure.com/mocking-http-requests-in-golang/

英文:

My suggestion is to first try abstracting the inputs that you sent to a method

Like instead of this

userToken, err := h.getBearer(req.Headers)

You can pass specify interfaces like

type userTokenInput struct {}
uti := userTokenInput{} 
userToken, err := h.getBearer(uti)

The above helps you to have control over input which makes testing easier

For network calls try using some mock HTTP client which can return expected
data you can follow this for mock HTTP client https://www.thegreatcodeadventure.com/mocking-http-requests-in-golang/

答案2

得分: 0

如果服务在没有令牌的情况下无法工作,你将需要提供一个令牌。

如果由于某种原因,你进行的调用不应该在真实目标系统上显示,你将需要一个不同的目标系统进行测试。

  • 询问提供者是否有可供使用的测试安装。
  • 考虑使用模拟进行测试。
英文:

If the service does not work without a token, you will have to provide one.

If the calls you will be doing should not be seen on the real target system for whatever reason, you will need a different target system for testing.

  • Ask the provider if they have a test installation you can use.
  • Consider testing against a mock.

huangapple
  • 本文由 发表于 2021年11月1日 15:05:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/69793589.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定