know-how.dev

How to test code with Zap?

2 years ago 1187

Zap - is a popular logging library for Golang. It allows easily Implement fast, configurable and structured logging for your go application.

package main

import "go.uber.org/zap"

func main() {
	logger, _ := zap.NewProduction()
	run(logger)
}

func run(logger *zap.Logger) {
	logger.Error("Hello World!")
}

And for testing zap provides zaptest package which allows not only mock logger, but also forwards logging to stdout when running tests (with -v flag).

package main

import (
	"testing"

	"go.uber.org/zap/zaptest"
)

func TestRun(t *testing.T) {
	logger := zaptest.NewLogger(t)
    run(logger)
}

Let's check the result.

$ go test -v

=== RUN   TestRun
    logger.go:130: 2022-04-26T10:24:15.502+0400	ERROR	Hello World!
--- PASS: TestRun (0.00s)
PASS
ok  	github.com/know-how/zap-test	0.116s