Test flags string

Hi guys, I’m trying to write a test for flags. I want to test the file that parses and validates the input. this file is like

options := Opt{
		Req1:       flag.String("file", "", ""),
		Req2: flag.String("address", "", ""),
		NotReq:    flag.String("age", "", ""),
}
flag.Parse()
boolean := validateIfInputIsCorrect(options)

and validateIfInputIsCorrect returns a bool true if the input contained the 2 required parameters and false if not.
I was trying in the _test.go file to set a flag string but then I get a panic error since it’s gonna parse it 2 times, any idea on how I can fix this?
Thanks

PS. this func has no input is like func Parse() (Options, bool)

Please show us your test code.

1 Like
func TestParse(t *testing.T) {
	var tests = configOptions{
		{Name: "Test 1", Flag: "file", Input: "blabla.txt", Output: true},
		{Name: "Test 2", Flag: "address", Input: "Steet 2", Output: true},
	}
	for _, testCase := range tests {
		t.Run(testCase.Name, func(t *testing.T) {
			flag.String(testCase.Flag, testCase.Input, "")
			_, boolean := Parse() //this is the func to test
			assert.Equal(t, testCase.Output, boolean)
		})
	}
}

Hi, @wecandoit,

Take a look at how the flag package itself tests flags here with a flag set.

1 Like

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