mercredi 3 avril 2019

How to mock user interaction functions in go? [duplicate]

This question already has an answer here:

I want to mock user input functions for testing purposes. Instead of requiring user input for tests, I want to just return a hard coded value. So to do this I created separate functions for the user input and assigned them to a var. In the tests I am just assigning the same var to a new function that just returns hardcoded values. However, when trying to test it, I get a declared and not used error.

This is my main program:

var getUserInput := func() string {
   //get user input through keyboard
}

func doStuff(){
    input := getUserInput()
    //do other stuff
}
func main() {
    doStuff()
    // do other stuff
}


And then to test this program, I have the following in another file, but same package:

func TestProgram(t *testing.T){
    var getUserInput := func() string {
        return "foo"
    }

    doStuff()
}

The error I get is getUserInput declared and not used but I expect it to use the reassigned var in doStuff().

Aucun commentaire:

Enregistrer un commentaire