AlecAivazis/survey

Testing survey.AskOne method with custom input

denizgursoy opened this issue · 1 comments

How can I provide input from byte array or text file for survey? I want to use it for test purposes.When I ask for input, I want to send mock value. Example code:

result := ""

input := survey.Input{
	Message: direction,
}
err := survey.AskOne(&input, &result, survey.WithValidator(survey.Validator(validator)))
return result, err

Hi, mocking Survey responses currently isn't straightforward and will only become easier after #428.

In the meantime, you can set up a virtual terminal in your tests to simulate user input to your prompt: https://github.com/AlecAivazis/survey#testing. Note that this also isn't straightforward.

My personal choice would be to declare a Prompter type in your code that has a method like PromptInput that uses Survey under the hood:

func (p Prompter) PromptInput(message string, validator func(string) bool) (string, error) {
	var result string
	err := survey.AskOne(&survey.Input{
		Message: direction,
	}, &result, survey.WithValidator(survey.Validator(validator)))
	return result, err
}

Then, in test mode, pass a mock object to your app that responds to PromptInput() but returns pre-defined fake responses. That way, Survey never gets actually invoked in tests, and you avoid a whole lot of trouble.