Viper - How to mock configuration for Testing


(Santhosh) #1

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.


(Ali Koyuncu) #2

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


(Santhosh) #3

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


(Ali Koyuncu) #4

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