Junior — Middle
What methods and tools are used to check and test code in Go?
sobes.tech AI
Answer from AI
In Go, the built-in package testing is used for code testing and verification. It allows writing unit tests that are run with the command go test.
Main methods and tools:
- Unit tests: created in files with the suffix
_test.go. Test functions should have the signaturefunc TestXxx(t *testing.T). - Benchmarks: functions with the signature
func BenchmarkXxx(b *testing.B)for measuring performance. - Mocks and stubs: can be created manually or using third-party libraries to simulate dependencies.
- Code coverage: using
go test -cover, you can get a report on test coverage.
Example of a simple test:
package mypackage
import "testing"
func Add(a, b int) int {
return a + b
}
func TestAdd(t *testing.T) {
result := Add(2, 3)
if result != 5 {
t.Errorf("Add(2, 3) = %d; want 5", result)
}
}
Also, for static analysis and code quality checks, tools like golint, go vet, and staticcheck are often used.