About go unit test, content contains:
- Why Unit Test
- Basic Knowledge
- Table Testing
- Testing HTTP
- Other Packages
- Other Mock Packages
- Testing with Docker
2. Agenda
? Why Unit Test
? Basic Knowledge
? Table Testing
? Testing HTTP
? Other Packages
? Other Mock Packages
? Testing with Docker
3. Why Unit Test
? Finds bugs early
? Debugging process
? Avoids breaking old code
? Quality of code
? Reduce costs
? Makes the process agile
? ´..
Find
Debug
Refactor
Improve
Reduce
Make agile
Reference https://dzone.com/articles/top-8-benefits-of-unit-testing
6. Why not yet
? Lack of basic knowledge
? Don't know how to use tools
? Don't know how to mock
? Writing not boring unit tests not easy
7. Basic knowledge
? Tests are written on files ending with "_test.go"
? Test function starts with Test* and has only the parameter *testing.T
? Use go test command to run your tests
https://golang.org/pkg/testing
8. go test
? go test // testing the local package
? go test some/pkg // testing a specific package
? go test some/pkg/´ // testing a specific package in recursive
? go test -v some/pkg Crun ^TestSum$ // runs a specified tests
? go test -cover // code coverage
? go test -count=1 // testing without cache
? ´.
https://golang.org/pkg/cmd/go/internal/test/
9. Table Testing
A example about IPV4 regexp:
`^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-
5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-
9]|25[0-5])$`
10. Table Testing
? Using anonymous structs to
represent test cases
? Using Subtests with t.Run
11. Testing HTTP
A example about user login
? Read body
? Unmarshal LoginForm
? Check Input data
12. Testing HTTP
? Use httptest.NewRecorder no need
listen
? Use errorReader to improve coverage
https://golang.org/pkg/net/http/httptest
14. Testify
? Run within go test
? Assertions, mostly shortcuts
? Mocking
https://github.com/stretchr/testify (10k+ stars)
15. GinkGo
? BDD
? Work with go test, but has it's own structure
? Uses a custom lib for assertion (Gomega)
? Rerun testes on change
https://github.com/onsi/ginkgo (4k stars)
https://en.wikipedia.org/wiki/Behavior-driven_development
18. GoConvey
? BDD alike
? Work with go test
? Pretty browser interface
? Reload tests on file changes
? Custom DSL
? goconvey || go test
https://github.com/smartystreets/goconvey (5.7k stars)
35. Go docker image
A example to run our tests
docker run --volume=$(pwd):/ws --
workdir=/ws golang:1.13.10
/bin/bash -c "GOPROXY=off go test -
v -cover -count=1 -mod=vendor ./...
https://hub.docker.com/_/golang
37. Conclusion
? Unit test should be a consensus
? Unit test in go is easy
? Mock make our testing efficient
? Service should be an interface for mock friendly
? Standard lib is good enough (table testing, testing HTTP)
? Other frameworks make testing better and documentation
? Docker can be used for more complex environment