Logging in tests
Often additional logging functionality is useful for tests to show the state of critical variables, especially if a failure occurs. By default, the Go test executor does not print any logging information if tests pass, but if a test fails, the logging information is also included in the output.
How to do it...
- Use
testing.T.Log
andtesting.T.Logf
functions to record log messages in tests:func TestSortTimeAscending(t *testing.T) { ... t.Logf("Input: %v",input) output:=SortTimes(input,true) t.Logf("Output: %v", output)
- Run the tests. If the test passes, no log information will be printed. If the test fails, logs will be printed.
To run the tests with logs, use the
-
v
flag:$ go test -v === RUN TestSortTimesAscending sort_test.go:17: Input: [2023-02-01 12:08:37 -0700 MST 2021-05-06 09:48:11 -0600 MDT 2022-11-13 17:13:54 -0700 MST 2022-06-23 22:29:28 -0600 MDT 2023-03-17 04:05:09 -0600 MDT] sort_test.go:19: Output: [2021-05-06 09:48:11 -0600 MDT 2022-06-23 22:29:28 -0600 MDT 2022-11-13 17:13:54 -0700 MST 2023-02-01 12:08:37 -0700 MST 2023-03-17 04:05:09 -0600 MDT] --- PASS: TestSortTimesAscending (0.00s)