Module 6: Testing and Benchmarking
Detailed Topics:
Unit Testing
Unit testing is the process of writing tests to verify that individual units of code (e.g., functions or methods) behave as expected. Unit tests in Go can be written using the built-in testing
package.
Key Points (1):
Unit tests are functions with names starting with
Test
, e.g.,TestAdd
.Use
t.Error
ort.Errorf
to report test failures.Organize tests in a
_test.go
file.
Example (1):
Table-Driven Tests
Table-driven tests use a table (a slice of structs) to organize test inputs and expected outputs. This approach simplifies managing multiple test cases.
Key Points (2):
Useful for functions with multiple test cases.
Improves readability and reduces code duplication.
Example (2):
Benchmarking
Benchmarking measures the performance of your code. Go provides support for benchmarking via the testing
package with functions prefixed by Benchmark
.
Key Points (3):
Benchmarks use
b *testing.B
as an argument.Use
b.N
to control the number of iterations.Focus on optimizing code based on benchmark results.
Example (3):
Detailed Hands-On
1. Write and Run Unit Tests for a Calculator Package
Create a
calculator
package with functionsAdd
,Subtract
,Multiply
, andDivide
.Write unit tests for each function, using both standard and table-driven approaches.
Run tests using:
go test ./...Verify all tests pass.
Example (4):
2. Benchmark Sorting Algorithms and Optimize Performance
Implement different sorting algorithms (e.g., Bubble Sort, Merge Sort).
Write benchmarks for each algorithm.
Analyze the benchmark results and optimize the slower algorithms.
Run benchmarks using:
go test -bench .
Example (5):
By completing these exercises, you will gain practical experience in writing robust tests and analyzing code performance.