Questions
How do you write tests in Go?
The Scenario
You are a backend engineer at a fintech company. You are writing a new service that needs to be well-tested.
You need to write unit tests, integration tests, and benchmarks for your code.
The Challenge
Explain how you would write tests in Go. What are the key features of the Go testing framework, and how would you use them to write different types of tests?
A junior engineer might not be aware of the built-in testing framework in Go. They might try to write their own testing framework, which would be a waste of time. They might also not be aware of the different types of tests and when to use each one.
A senior engineer would know that Go has a powerful built-in testing framework. They would be able to explain how to use the `testing` package to write unit tests, integration tests, and benchmarks.
Step 1: Understand the testing Package
The testing package is a built-in package in Go that provides support for testing.
| Feature | Description |
|---|---|
testing.T | A type passed to Test functions to manage test state and support formatted test logs. |
t.Run() | Used to create subtests. |
t.Error() | Used to report a test failure. |
t.Fatal() | Used to report a test failure and stop the test. |
testing.B | A type passed to Benchmark functions to manage benchmark state and run the benchmark. |
Step 2: Write a Unit Test
Here’s how we can write a simple unit test:
// main_test.go
package main
import "testing"
func TestMyFunction(t *testing.T) {
// ... (your test code) ...
}To run the tests, you can use the go test command.
Step 3: Write an Integration Test
You can use build tags to separate your integration tests from your unit tests.
// +build integration
package main
import "testing"
func TestMyIntegration(t *testing.T) {
// ... (your integration test code) ...
}To run the integration tests, you can use the go test -tags=integration command.
Step 4: Write a Benchmark
Here’s how we can write a simple benchmark:
// main_test.go
package main
import "testing"
func BenchmarkMyFunction(b *testing.B) {
for i := 0; i < b.N; i++ {
MyFunction()
}
}To run the benchmarks, you can use the go test -bench=. command.
Practice Question
You want to run only the integration tests in your project. Which of the following commands would you use?