How to Effectively Print Messages in Go Tests
During testing in Go, it can be useful to print messages for debugging purposes. However, using fmt.Println does not always produce the expected output. Instead, the following methods provide more reliable printing options when working with tests.
Testing.T and Testing.B Logging Methods:
Both testing.T and testing.B structs provide the following logging methods:
These methods are specifically designed for use in tests and ensure that the printed messages are appropriately handled.
Example:
func TestPrintSomething(t *testing.T) { t.Log("Say hi") // Prints "Say hi" using the .Log method }
Test Output with -v Flag:
Standard fmt.X print statements can indeed work within tests. However, their output may not be displayed immediately on the screen. To see the output, the "-v" (verbosity) flag must be passed to go test.
go test -v
With the "-v" flag, the test will print the log messages for both passing and failing tests.
Note:
The .Error method of testing.T can also be used to print messages. However, it is intended for reporting errors and will mark the test as failed. The .Log methods provide a cleaner and more suitable option for informative printing without affecting the test result.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3