I'm writing test code for my code and would like to get 100% code coverage.
This implies testing corner cases that calls glog.Fatal()
for instance.
So first thing I need is to disable any output by glog because I'm not testing glog. So I can run go test without generating files in /tmp
or spittig messages to stderr
.
The second thing I need is that a call to glog.Fatal()
which calls os.Exit()
doesn't interfere with running the test.
How could I achieve that ?
You should be able to achieve it by programming to the glog
interface. I'm not sure what that is but it could look like
type Logger interface {
Fatal()
Info()
// etc...
}
Then your packages/functions/structs etc, would have to require the interface opposed to including a global.
type SomeStruct struct {
log Logger
}
Or on your top level modules:
func SomeFunc(log Logger) {}
Using an interface decouples your code from a loggers specific implementation.
In your unit tests you can create a test specific logger, which is a stub, or a mock.
type TestLogger struct {}
func (tl TestLogger) Fatal() {}
func (tl TestLogger) Info() {}
// etc....
Then your code has to be able to instantiate and configure the real Glog
instance, in your production code. To test this, it should be as simple as encapsulating "creating" a Glog instance.
func NewLogger Logger {
// configure `Glog`
// return `Glog`
}
This way you should be able to unit test the NewLogger
configures a logger correctly without actually having to make calls to the logger.