如何使用反射创建接口值类型的对象

How to create an object of interface value type in go using reflection

已更新

我想制作辅助函数来测试读取环境变量函数。它使用 envconfig.

func Test_T2(t *testing.T) {

    os.Setenv("APP_PARAM_STR", "string value")
    os.Setenv("APP_PARAM_INT", "12")

    os.Setenv("APP_PARAM_DURATION", "15s")
    os.Setenv("APP_PARAM_INT", "44")

    c := ConfigTwo{}

    d := ConfigTwo{
        ParamDuration: 15*time.Second,
        ParamInt:      44,
    }

    helper(t, &c, &d)
}

func helper(t *testing.T, confObject, expValue interface{}) {
    t.Helper()

    err := getParams(&confObject)
    if !assert.NoError(t, err) {
        return
    }

    assert.Equal(t, expValue, confObject)
}

func getParams(cfg interface{}) error {
    return envconfig.Process("APP", cfg)

}

** UPDATE 2 **
It works. Thanks everyone.

如果我只有 getPrams 功能,它就可以工作。但是如果我添加助手(我需要测试不同的结构),我会得到一个错误: specification must be a struct pointer

envconfig 执行两次检查 here:

使用此代码。参数是指向期望值的指针。

func helper(t *testing.T, pexpected interface{}) {
    t.Helper()
    pactual := reflect.New(reflect.TypeOf(pexpected).Elem()).Interface()

    err := getParams(pactual)
    if !assert.NoError(t, err) {
        return
    }

    assert.Equal(t, pexpected, pactual)
}

表达式 reflect.New(reflect.TypeOf(pexeceted).Elem()).Interface() returns 指向与 pexpected 指向的类型相同的新空值的指针。

这样称呼它:

helper(t, &ConfigTwo{A: "expected A Field", B: "expected B field"}