Explain integration testing vs unit testing

4 minintermediatetestingintegration-testingunit-testing

Quick Answer

Unit tests verify a single component in isolation (dependencies faked), are fast, and pinpoint failures precisely. Integration tests verify that multiple components work together — real database, HTTP pipeline, or external services — catching wiring, configuration, and contract issues that unit tests miss, at the cost of being slower and broader. A healthy suite uses many fast unit tests and fewer, targeted integration tests.

Detailed Answer

Unit Testing:

  • Tests individual components in isolation
  • Fast execution (milliseconds)
  • No external dependencies
  • Uses mocks/stubs for dependencies
  • Runs frequently (every build)
  • Large number of tests
  • Focuses on single method/class behavior
[Fact]
public void CalculateDiscount_PremiumCustomer_Returns20Percent()
{
    var calculator = new DiscountCalculator();
    var result = calculator.Calculate(100, CustomerType.Premium);
    Assert.Equal(20, result);
}

Integration Testing:

  • Tests how components work together
  • Slower execution (seconds to minutes)
  • Uses real dependencies (database, APIs, file system)
  • Tests interactions between modules
  • Runs less frequently (pre-commit, CI/CD)
  • Fewer tests than unit tests
  • Focuses on component collaboration
[Fact]
public async Task CreateOrder_ValidData_SavesToDatabase()
{
    // Uses real database (or test database)
    var dbContext = new OrderContext(connectionString);
    var repository = new OrderRepository(dbContext);
    var service = new OrderService(repository);
    
    var order = new Order { CustomerId = 1, Total = 100 };
    await service.CreateOrder(order);
    
    var saved = await dbContext.Orders.FindAsync(order.Id);
    Assert.NotNull(saved);
    Assert.Equal(100, saved.Total);
}

Comparison Table:

AspectUnit TestingIntegration Testing
ScopeSingle unitMultiple components
SpeedVery fastSlower
DependenciesMockedReal
IsolationCompletePartial
QuantityHundreds/ThousandsDozens/Hundreds
ComplexitySimpleComplex
MaintenanceEasyMore difficult
When to RunEvery buildCI/CD pipeline

Best Practice: Use both! Follow the testing pyramid:

  • 70% Unit Tests (base)
  • 20% Integration Tests (middle)
  • 10% E2E/UI Tests (top)