首页 > 解决方案 > 在测试 http 请求时使用 Golang context.WithValue

问题描述

我正在尝试进行单元测试,我在gqlgenEcho 的这种情况下使用 GraphQL,我一直在努力用我的上下文进行测试,由于 GraphQL 不使用服务器端点,我无法在测试中添加标头这是我的代码设置上下文值

var ctx *http.Request
var echo echo.Context

h := context.WithValue(ctx.Context(), "Token", token)
tk := ctx.WithContext(h)
echo.SetRequest(tk)

我在运行服务器时在中间件功能上执行此操作,没有问题,这是我在解析器中的调用方式

// c is context.Context
tokenHeader = c.Value("Token")

但在测试中,我创建的代码总是得到:

panic: runtime error: invalid memory address or nil pointer dereference [recovered]
        panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x1703953]

goroutine 30 [running]:
testing.tRunner.func1.1(0x17b3000, 0x1f47810)
        /usr/local/Cellar/go/1.14.3/libexec/src/testing/testing.go:940 +0x2f5
testing.tRunner.func1(0xc000378900)
        /usr/local/Cellar/go/1.14.3/libexec/src/testing/testing.go:943 +0x3f9
panic(0x17b3000, 0x1f47810)
        /usr/local/Cellar/go/1.14.3/libexec/src/runtime/panic.go:969 +0x166
spur/test.TestCredential.func3(0xc000378900)
        /Users/me/Documents/project/test/main_test.go:144 +0x193
testing.tRunner(0xc000378900, 0xc00034fdf0)
        /usr/local/Cellar/go/1.14.3/libexec/src/testing/testing.go:991 +0xdc
created by testing.(*T).Run
        /usr/local/Cellar/go/1.14.3/libexec/src/testing/testing.go:1042 +0x357

是否可以在测试期间设置上下文值?

这是完整的测试代码:


func TestCredential(t *testing.T)  {
    config := resolver.Config{
        Resolvers: resolver.New(),
    }

    clientTest := testClient.New(handler.NewDefaultServer(resolver.NewExecutableSchema(config)))

    t.Run("Should Success Change Password", func(t *testing.T) {
        var ctx *http.Request
        var echo echo.Context

        h := context.WithValue(ctx.Context(), "Token", token)
        tk := ctx.WithContext(h)
        echo.SetRequest(tk)


        var respond map[string]interface{}
        mutation := `mutation {
                      changeCredentialConfirmation(
                        currentPassword: ""
                        newChange: "newPassword"
                        isForgotPassword: true
                        isChangePassword: false
                      )
                    }`
        clientTest.MustPost(
            mutation,
            &respond,
        )
        require.True(t, respond["changeCredentialConfirmation"].(bool), "Check your email")
    })
}

标签: unit-testinggographqlgo-echogo-testing

解决方案


推荐阅读