What tools and approaches do you use for integration testing in your projects?
sobes.tech AI
Answer from AI
For integration tests in Go projects, I usually apply the following approaches and tools:
-
Test frameworks: the standard
testingpackage along with libraries liketestifyfor convenient assertions. -
Environment isolation: using Docker containers to set up dependencies (databases, cache, external services) in the test environment.
-
Test data: preparing fixtures or using migrations to create the necessary database state before tests.
-
Mock and stub: for external services, if integration with them is not mandatory or too costly.
-
CI/CD integration: running integration tests in pipelines for automatic verification.
Example of a simple integration test using testing and connecting to a test database:
func TestCreateUserIntegration(t *testing.T) {
db, err := sql.Open("postgres", "connection_string_to_test_db")
if err != nil {
t.Fatal(err)
}
defer db.Close()
userRepo := NewUserRepository(db)
user := User{Name: "Test User", Email: "test@example.com"}
err = userRepo.Create(user)
if err != nil {
t.Errorf("failed to create user: %v", err)
}
// Check that the user was actually created
savedUser, err := userRepo.FindByEmail(user.Email)
if err != nil || savedUser == nil {
t.Errorf("user not found after creation")
}
}
Thus, integration tests verify the interaction of multiple system components together.