Sobes.tech
Junior

How do unit tests differ from integration tests?

sobes.tech AI

Answer from AI

Unit tests and integration tests differ in coverage and goals:

  • Unit tests check individual, isolated parts of the code — usually functions or methods. They do not depend on external systems (databases, networks, etc.) and run quickly. The goal is to ensure that a specific module works correctly.

  • Integration tests check the interaction of multiple components or modules together. They may use real databases, services, and other external dependencies. The goal is to ensure that components work correctly together.

Example in Go:

// Unit test for a function
func TestAdd(t *testing.T) {
    result := Add(2, 3)
    if result != 5 {
        t.Errorf("Expected 5, got %d", result)
    }
}

// Integration test with a database
func TestUserCreation(t *testing.T) {
    db := setupTestDB()
    userService := NewUserService(db)
    err := userService.CreateUser("testuser")
    if err != nil {
        t.Fatal(err)
    }
    // Check that the user was actually created in the DB
}

Thus, unit tests focus on logic, while integration tests focus on component interaction.