I'm trying to write a unit test in go for a function that returns non-zero exit codes. I'm developing a CLI app with cobra to validate semantic versions. In case a validation fails, I return some information in JSON and exit with os.Exit(1)
.
Now I want to test if this really works as intended. In my test I pass with one data set that should success and return 0 and one that should fail and return 1. But the test that should return 1 always cancels the test and hence cancels all following iterations. This is my code:
func Test_ShouldGetCorrectExitCode(t *testing.T) {
testCases := []struct {
args []string
shouldBeValid bool
}{
{[]string{"0.1.0"}, false},
{[]string{"v0.1.0"}, true},
}
for _, tc := range testCases {
assert := assert.New(t)
cmd := NewCmdValidate()
cmd.SetArgs(tc.args)
err := cmd.Execute()
assert.Nil(err)
}
}
So far the assertions are not really sophisticated because I don't get the test to run the way I expect. Anyone got an idea how I can test for exit codes in go?