Sobes.tech
Junior — Middle

Why are stubs and mocks used in software testing?

sobes.tech AI

Answer from AI

Stubs and mocks are used in testing to isolate the component under test from external dependencies.

  • Stubs provide fixed responses to calls, allowing to verify system behavior under certain conditions.
  • Mocks not only provide responses but also verify which methods were called with what parameters.

This helps to:

  • Test components independently of external services, databases, network calls.
  • Create controlled scenarios to test error handling and boundary cases.
  • Speed up test execution by avoiding real-time costs of external operations.

Example in Go using an interface and a stub:

// Interface for external service
type DataFetcher interface {
    FetchData() (string, error)
}

// Stub for testing
type StubFetcher struct{}

func (s StubFetcher) FetchData() (string, error) {
    return "test data", nil
}

// In a test, you can use StubFetcher instead of a real service
Why are stubs and mocks used in software testing… - sobes.tech