Disable Log Output During Tests

· 232 words · 2 minutes read

It’s quite common to use the log package within your code to keep track of things which the end user might not need to see, like deprecated notices and warnings. These are great when they are in production and you are monitoring the logs - but they will show up during your tests.

Below is an example test for our example application (even further below) which just asserts that the result of the function is 5. But this same function call also uses log.

To disregard the logs for these tests we use the TestMain function, set the logging output to discard then run our tests by calling run.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
package main

import (
	"testing"
	"log"
	"io/ioutil"
	"os"
)

// SETUP
// Importantly you need to call Run() once you've done what you need
func TestMain(m *testing.M) {
	log.SetOutput(ioutil.Discard)
	os.Exit(m.Run())
}

func TestDoAndLogSomething(t *testing.T) {
	// Basic Test Example
	if result := DoAndLogSomething(); result != 5 {
		t.Errorf("TestDoAndLogSomething returned an unexpected number: got %v want %v", result, 5)
	}
}

Our Example Application:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package main

import "log"

func main() {
	DoAndLogSomething()
}

func DoAndLogSomething() int {
	log.Println("Hello GoLangCode.com")
	return 5
}

Screenshot of without and with the discard option:

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!