Course contentsShow
← Software Engineering
Lesson 537 of 1,93316. Integration TestingFree lesson

Network and Service Discovery in Tests

Managing network configuration, ports, and service discovery when running multiple real services in integration tests.

Network and Service Discovery in Tests

What You'll Learn

You'll learn how to manage network configuration, ports, and service discovery when your integration tests spin up multiple real services that need to find and communicate with each other.

The Problem with Multiple Services

When testing systems that involve several services (a database, a web server, a message broker), each needs its own network port. If you hardcode localhost:5432 for your database, what happens when multiple test suites run simultaneously? Port conflicts arise, tests fail unpredictably, and you get flaky results.

Think of it like parking spots: If you tell everyone to park in spot #5, chaos ensues when multiple cars arrive at once.

Dynamic Port Allocation

Instead of hardcoding ports, let the operating system assign random available ports. When you start a test service, ask for port 0 (which means "give me any free port"), then retrieve the actual assigned port to configure your application.

# Dynamic port assignment
test_db_port = test_container.get_mapped_port("5432/tcp")
app_config.database_url = f"localhost:{test_db_port}"

Service Discovery Patterns

When Service A needs to talk to Service B in tests:

  1. Environment Variables: Pass connection strings as environment variables to each service during test startup
  2. Configuration Files: Generate temporary config files with actual runtime addresses
  3. Wait Strategies: Don't assume services are ready immediately—poll or wait for health endpoints before running tests

Modern test containers handle much of this automatically, exposing methods to retrieve dynamic connection details after startup.

Avoiding Race Conditions

Services may start but not be ready. Always implement readiness checks: repeatedly attempt connections or HTTP health checks until the service responds correctly, with reasonable timeouts.

Key Takeaway: In integration tests with multiple services, use dynamic port allocation and service discovery mechanisms instead of hardcoded addresses to avoid conflicts and enable parallel test execution.