Yura
Yura

Reputation: 1174

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

UPDATED

I want to make helper function for testing reading env vars function. It uses 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.

It works if I have getPrams function only. But if I add helper (that I need to test different structs) I get an error: specification must be a struct pointer

envconfig performs two checks here:

Upvotes: 3

Views: 1993

Answers (1)

user12258482
user12258482

Reputation:

Use this code. The argument is a pointer to the expected value.

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)
}

The expression reflect.New(reflect.TypeOf(pexeceted).Elem()).Interface() returns a pointer to a new empty value with the same type as what pexpected points to.

Call it like this:

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

Upvotes: 3

Related Questions