Testing in Go
The Bug That Cost Us $2,847
func calculateDiscount(price float64, couponCode string) float64 {
discount := 0.0
if couponCode == "SAVE10" {
discount = price * 0.10
} else if couponCode == "SAVE20" {
discount = price * 0.20
}
// BUG: Forgot to subtract discount!
return price
}Test-Driven Development (TDD)
The Corrected Version (TDD Style)
Testing Basics
File Naming Convention
Test Function Signature
Running Tests
Table-Driven Tests
Basic Pattern
Real Example: Email Validator
Test Coverage
Measuring Coverage
Example with Coverage Analysis
Benchmarks
Basic Benchmark
Real Example: String Concatenation
Example Tests
Test Helpers and Utilities
Helper Functions
Setup and Teardown
Subtests
Testify Library
Installation
Assertions
Require (Stops Test on Failure)
Common Assertions
Mocking Strategies
Interface-Based Mocking
Testify Mock
Real Example: Testing HTTP Handlers
Real Project: Complete Test Suite
Your Challenge
Key Takeaways
What I Learned
Last updated