Viper - How to mock configuration for Testing

Hi,

I am a beginner in Golang programming and I have problem while testing my service.

I have a configuration file like this in my yml file:
service:
max:
limit: 5
error: false

I am using Viper to read the configuration, e.g.

maxerror =config.Viper.GetString("service.max.error")

Assume that I have a condition in code,
if strings.EqualFold(maxerror, "true") {
//do something
} else{
//do otherwise
}

My config for “service.max.error” is set to “true”. So while testing, only the “if block” executes. How do I mock/overwrite the property value to test the “else” block.

1 Like

Could you please put the codes in the code block and make it more readable?

1 Like

@kync, thanks for your input. I have updated code section. Can you kindly recheck the post now?

1 Like

Change your function/method to take a parameter from outside and pass the maxError as a parameter to this function. Try to avoid inject dependencies into your functions.

Read viper, get max error

 //maxError := config.Viper.GetString("service.max.error")
 func doSomething(maxError string) (ret interface{}){
    if strings.EqualFold(maxerror, "true") {
    //do something
    } else{
    //do otherwise
    }
}

func TestDoSomething(t *testing.T){
    retVal :- doSomething(5)
    if retVal  != 5{
        t.Errorf("doSomething(5) = %d; want 5", retVal)
    }
}
2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.