VOOZH about

URL: https://deepwiki.com/hypervel/foundation/6.5-container-and-service-testing

⇱ Container and Service Testing | hypervel/foundation | DeepWiki


Loading...
Last indexed: 7 February 2026 (101eff)
Menu

Container and Service Testing

Purpose and Scope

This document covers the container and service testing capabilities provided by the InteractsWithContainer trait. This trait enables test cases to manipulate the application's dependency injection container, allowing developers to mock services, swap implementations, and control the test environment's service resolution behavior.

For information about the foundational test case lifecycle, see Test Case Foundation and Lifecycle. For HTTP-specific testing utilities, see HTTP Request Testing.

Sources: src/Testing/Concerns/InteractsWithContainer.php1-111


InteractsWithContainer Trait Overview

The InteractsWithContainer trait is the primary interface for manipulating the application container during tests. It provides methods for service registration, mocking, spying, and application lifecycle management, ensuring tests can control their dependency injection environment.

Core Capabilities

CapabilityMethodsPurpose
Service Registrationinstance(), swap()Replace container bindings with specific instances
Mockingmock(), partialMock()Create Mockery mock objects and bind them to the container
Spyingspy()Create Mockery spy objects for method call verification
Mock ManagementforgetMock()Remove previously registered mocks from the container
Application LifecyclerefreshApplication(), flushApplication()Control application instance creation and destruction
Environment CustomizationdefineEnvironment()Hook for customizing the application before tests

Sources: src/Testing/Concerns/InteractsWithContainer.php17-111


InteractsWithContainer Architecture


Diagram: InteractsWithContainer trait methods and their relationships with the Application container and external dependencies

Sources: src/Testing/Concerns/InteractsWithContainer.php17-111


Service Registration and Swapping

The trait provides two primary methods for registering service instances in the container during tests.

instance() Method

The instance() method registers a specific object instance as the resolution for a given abstract type. When the container resolves that abstract, it will return the registered instance.


Behavior:

  • Calls $this->app->set($abstract, $instance) to register the instance src/Testing/Concerns/InteractsWithContainer.php38-44
  • Returns the registered instance for convenient chaining
  • The instance will be returned for all subsequent container resolutions of $abstract

swap() Method

The swap() method is an alias for instance(), providing semantic clarity when replacing an existing service binding.


Behavior:

Sources: src/Testing/Concerns/InteractsWithContainer.php27-44


Mocking and Spying with Mockery

The trait integrates Mockery for creating mock and spy objects, automatically registering them in the container.

mock() Method

Creates a full Mockery mock object and registers it in the container. All method calls on the mock must be explicitly expected or the mock will fail.


Parameters:

  • $abstract: The service identifier to mock
  • $mock: Optional closure for configuring mock expectations

Implementation:

partialMock() Method

Creates a partial Mockery mock where only explicitly mocked methods are affected; unmocked methods execute their original implementation.


Implementation:

spy() Method

Creates a Mockery spy object that records method calls without preventing the original implementation from executing.


Implementation:

Sources: src/Testing/Concerns/InteractsWithContainer.php49-68


Mock vs Spy vs Instance Decision Flow


Diagram: Decision flowchart for choosing between mock, spy, partialMock, and instance methods

Sources: src/Testing/Concerns/InteractsWithContainer.php27-68


Mock Management

forgetMock() Method

Removes a previously registered mock or instance from the container, allowing the container to resolve the service normally again.


Behavior:

Use Case: When testing multiple scenarios in the same test method where some scenarios need mocked services and others need real implementations.

Sources: src/Testing/Concerns/InteractsWithContainer.php75-80


Application Lifecycle Management

The trait provides methods for controlling the application instance lifecycle, enabling proper test isolation and environment customization.

Application Lifecycle Flow


Diagram: Application lifecycle management during test execution

Sources: src/Testing/Concerns/InteractsWithContainer.php82-111


refreshApplication() Method

Recreates the application instance with proper test environment configuration.


Execution Sequence:

  1. Create Application: Calls createApplication() to instantiate a new application src/Testing/Concerns/InteractsWithContainer.php89
  2. Bind Test Dispatcher: Replaces HttpDispatcher::class with TestingHttpDispatcher::class src/Testing/Concerns/InteractsWithContainer.php91
  3. Bind Database Resolver: Replaces ConnectionResolverInterface::class with DatabaseConnectionResolver::class src/Testing/Concerns/InteractsWithContainer.php92
  4. Define Environment: Calls defineEnvironment($app) hook src/Testing/Concerns/InteractsWithContainer.php94
  5. Initialize Application: Forces container initialization by resolving ApplicationInterface::class src/Testing/Concerns/InteractsWithContainer.php96

Test Bindings:

ServiceTest ImplementationPurpose
HttpDispatcher::classTestingHttpDispatcher::classEnables HTTP request simulation in tests
ConnectionResolverInterface::classDatabaseConnectionResolver::classProvides test-specific database connection handling

Sources: src/Testing/Concerns/InteractsWithContainer.php87-97


flushApplication() Method

Clears the current application instance, preparing for cleanup or recreation.


Behavior:

Sources: src/Testing/Concerns/InteractsWithContainer.php82-85


createApplication() Method

Factory method for creating the application instance.


Implementation:

Sources: src/Testing/Concerns/InteractsWithContainer.php107-110


defineEnvironment() Hook

Provides a hook for customizing the application environment before tests execute.


Purpose:

Timing: Called during refreshApplication(), after test bindings are registered but before the application is fully initialized src/Testing/Concerns/InteractsWithContainer.php94

Sources: src/Testing/Concerns/InteractsWithContainer.php102-105


Container Testing Patterns

Pattern: Mocking External Services


Diagram: Flow of mock object creation and usage in container testing

When testing code that depends on external services (APIs, databases, file systems):

  1. Use mock() to create and register a mock in the container
  2. Set expectations on the mock object
  3. Execute the code under test
  4. Mockery automatically verifies expectations

Sources: src/Testing/Concerns/InteractsWithContainer.php49-52


Pattern: Partial Service Replacement

When testing code that uses a service where you only need to override specific methods:

  1. Use partialMock() to preserve original method implementations
  2. Only stub the methods that need different behavior
  3. Remaining methods execute their real implementation

Sources: src/Testing/Concerns/InteractsWithContainer.php57-60


Pattern: Verifying Service Interactions

When you need to verify that code calls specific service methods without preventing execution:

  1. Use spy() to create a transparent spy object
  2. Execute the code under test
  3. Use shouldHaveReceived() to verify method calls
  4. Original service methods execute normally

Sources: src/Testing/Concerns/InteractsWithContainer.php65-68


Pattern: Environment-Specific Test Setup

When different tests require different application configurations:

  1. Override defineEnvironment() in your test class
  2. Use the $app parameter to configure the container
  3. Register test-specific bindings
  4. Set configuration values

Example Structure:


Sources: src/Testing/Concerns/InteractsWithContainer.php102-105


Integration with Test Case Lifecycle

The InteractsWithContainer trait integrates with the broader test case lifecycle defined in the TestCase base class.

Application Property

The trait declares a protected $app property that holds the current application instance src/Testing/Concerns/InteractsWithContainer.php19 This property is:

  • Set by refreshApplication()
  • Cleared by flushApplication()
  • Used by all service manipulation methods

Lifecycle Integration Points

PhaseMethodPurpose
Before Each TestrefreshApplication()Creates fresh application instance
During Testinstance(), mock(), spy()Manipulates container bindings
After Each TestflushApplication()Clears application instance
Custom SetupdefineEnvironment()Test-specific configuration

Sources: src/Testing/Concerns/InteractsWithContainer.php19-111


Summary

The InteractsWithContainer trait provides comprehensive facilities for controlling the application's dependency injection container during tests. Key capabilities include:

  • Service Registration: instance() and swap() for direct service replacement
  • Mocking: mock(), partialMock(), and spy() for Mockery integration
  • Mock Management: forgetMock() for removing test doubles
  • Application Lifecycle: refreshApplication(), flushApplication(), and createApplication() for test isolation
  • Environment Customization: defineEnvironment() hook for test-specific setup

These tools enable comprehensive test isolation and precise control over service resolution, allowing tests to focus on specific behaviors without interference from production dependencies.

Sources: src/Testing/Concerns/InteractsWithContainer.php1-111