Setup and Teardown
Understanding Setup and Teardown
Setup and teardown methods are crucial for preparing test environments and cleaning up resources after tests complete. Go provides multiple approaches to implement these strategies.
Types of Setup and Teardown
graph TD
A[Setup and Teardown] --> B[Package Level]
A --> C[Test Suite Level]
A --> D[Individual Test Level]
Package-Level Setup
Using init()
Function
package database
import (
"database/sql"
"testing"
)
var testDB *sql.DB
func init() {
// Setup before any tests run
db, err := sql.Open("postgres", "connection_string")
if err != nil {
panic(err)
}
testDB = db
}
func TestDatabaseOperations(t *testing.T) {
// Test using testDB
}
func TestClose(t *testing.T) {
if testDB != nil {
testDB.Close()
}
}
Test Suite Level Setup
Using Test Main
package integration
import (
"os"
"testing"
)
func TestMain(m *testing.M) {
// Setup before test suite
setupTestEnvironment()
// Run tests
code := m.Run()
// Teardown after all tests
teardownTestEnvironment()
os.Exit(code)
}
func setupTestEnvironment() {
// Prepare test resources
}
func teardownTestEnvironment() {
// Clean up resources
}
Individual Test Setup and Teardown
Inline Setup and Teardown
func TestUserCreation(t *testing.T) {
// Setup
tempDir, err := os.MkdirTemp("", "test-*")
if err != nil {
t.Fatalf("Cannot create temp directory: %v", err)
}
// Teardown
defer os.RemoveAll(tempDir)
// Test logic
}
Setup and Teardown Strategies
Strategy |
Scope |
Use Case |
init() |
Package |
Global setup |
TestMain() |
Test Suite |
Complex setup/teardown |
defer |
Individual Test |
Resource cleanup |
Advanced Setup Techniques
Table-Driven Test Setup
func TestCalculations(t *testing.T) {
testCases := []struct {
name string
input int
expected int
setup func() error
teardown func()
}{
{
name: "Positive Scenario",
input: 10,
expected: 20,
setup: func() error {
// Prepare specific test environment
return nil
},
teardown: func() {
// Clean up resources
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
if err := tc.setup(); err != nil {
t.Fatalf("Setup failed: %v", err)
}
defer tc.teardown()
// Perform test
})
}
}
LabEx Recommendation
When practicing setup and teardown techniques, LabEx suggests focusing on creating repeatable and isolated test environments that minimize side effects.
Best Practices
- Keep setup and teardown methods simple
- Ensure complete resource cleanup
- Handle potential errors during setup
- Use
defer
for automatic resource management
- Minimize global state modifications
Common Pitfalls
- Creating complex setup logic
- Forgetting to close resources
- Introducing test dependencies
- Neglecting error handling
Conclusion
Effective setup and teardown strategies are essential for creating reliable and maintainable test suites in Go. By understanding and applying these techniques, developers can create more robust testing environments.