Reputation: 62
I am writing a program in go with Cobra CLI framework , right now I am working on writing test files to the CLI, i have some prints that i want to check if correct but i couldn't figure out how to get the prints and compare them my code is like this:
func TestCommand(t *testing.T) {
// Start the mock server
mockServer, err := mock.StartMockServer()
if err != nil {
t.Fatalf("Failed to start mock server: %v", err)
}
defer mockServer.Stop() // Ensure the server is stopped after the test
// Wait for a moment to ensure the server is up
time.Sleep(100 * time.Millisecond)
// Capture output
var buf bytes.Buffer
rootCmd := cmd.NewRootCommand()
rootCmd.SetOut(&buf)
// Execute the command
rootCmd.SetArgs([]string{"version"})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("Execute() failed: %v", err)
}
// Check expected output
if buf.String() != ExpectedVersion {
t.Errorf("Expected %q, got %q", ExpectedVersion, buf.String())
}
}
and the output when i run go test is
=== RUN TestCommand
Connecting to server on localhost:4466...
Version: v0.22.0-15-gd09d7fca0d
/home/shoham/TraceeClient/cmd/cmd_test.go:44: Expected "Version: v0.22.0-15-gd09d7fca0d\n", got ""
--- FAIL: TestVersionCommand (0.17s)
as you can see the version prints to the screen but the buffer dont collect it, how can i fix this issue?
i have tried to print it diffrently then I use before, I have used the fmt.Println and fmt.Printf for this prints and it still didnt work when I try to use each one
Upvotes: 0
Views: 32