Class DummyConnection

java.lang.Object
com.lucimber.dbus.connection.DummyConnection
All Implemented Interfaces:
Connection, AutoCloseable

public class DummyConnection extends Object implements Connection
A dummy implementation of Connection for testing D-Bus applications without requiring a real D-Bus daemon, similar to Netty's EmbeddedChannel.

This class provides a complete implementation of the Connection interface that can be used in unit tests and integration tests. It simulates D-Bus behavior including connection lifecycle, message handling, and error conditions.

Key Features

  • No D-Bus daemon required - Works entirely in-memory
  • Configurable responses - Define custom responses for method calls
  • Connection lifecycle simulation - Realistic state transitions
  • Message capture - Inspect sent messages for verification
  • Error simulation - Test connection failures and recovery
  • Thread-safe - Safe for concurrent testing

Basic Usage


 @Test
 public void testMyService() {
     // Create a dummy connection
     DummyConnection connection = DummyConnection.create();

     // Define a custom response
     connection.setMethodCallResponse("com.example.Service", "GetData",
         DummyConnection.successResponse(List.of(DBusString.valueOf("test-data"))));

     // Connect and use in your service
     connection.connect().toCompletableFuture().get();
     MyService service = new MyService(connection);

     // Test the service
     String result = service.getData();
     assertEquals("test-data", result);

     // Verify the method was called
     assertTrue(connection.wasMethodCalled("com.example.Service", "GetData"));
 }
 

Advanced Testing


 @Test
 public void testConnectionFailure() {
     DummyConnection connection = DummyConnection.builder()
         .withConnectionFailure(true)
         .build();

     // Test how your code handles connection failures
     assertThrows(Exception.class, () -> connection.connect().toCompletableFuture().get());
 }

 @Test
 public void testMessageCapture() {
     DummyConnection connection = DummyConnection.create();
     connection.connect().toCompletableFuture().get();

     // Your code sends messages
     myService.performAction();

     // Verify messages were sent
     List<OutboundMessage> messages = connection.getSentMessages();
     assertEquals(1, messages.size());

     OutboundMethodCall call = (OutboundMethodCall) messages.get(0);
     assertEquals("PerformAction", call.getMember().toString());
 }
 

Error Testing


 @Test
 public void testErrorHandling() {
     DummyConnection connection = DummyConnection.create();
     connection.setMethodCallResponse("com.example.Service", "FailingMethod",
         DummyConnection.errorResponse("com.example.Error", "Something went wrong"));

     connection.connect().toCompletableFuture().get();

     // Test that your code handles D-Bus errors properly
     assertThrows(MyServiceException.class, () -> myService.callFailingMethod());
 }
 

Connection Events


 @Test
 public void testConnectionEvents() {
     DummyConnection connection = DummyConnection.create();
     AtomicBoolean connected = new AtomicBoolean(false);

     connection.addConnectionEventListener((conn, event) -> {
         if (event.getType() == ConnectionEventType.STATE_CHANGED
             && event.getNewState().orElse(null) == ConnectionState.CONNECTED) {
             connected.set(true);
         }
     });

     connection.connect().toCompletableFuture().get();
     assertTrue(connected.get());
 }
 

Thread Safety

This class is thread-safe and can be used in concurrent tests. All methods can be called from multiple threads without external synchronization.

Cleanup

Always call close() when done testing to clean up resources:


 @Test
 public void testWithCleanup() {
     DummyConnection connection = DummyConnection.create();
     try {
         // Your test code
     } finally {
         connection.close();
     }
 }
 
Since:
2.0
  • Method Details

    • builder

      public static DummyConnection.Builder builder()
      Creates a new builder for configuring a DummyConnection.
      Returns:
      a new Builder instance
    • create

      public static DummyConnection create()
      Creates a simple DummyConnection with default configuration.
      Returns:
      a new DummyConnection instance ready for use
    • connect

      public CompletionStage<Void> connect()
      Description copied from interface: Connection
      Initiates a connection to a D-Bus instance.
      Specified by:
      connect in interface Connection
      Returns:
      a CompletionStage that completes when the connection is established, or exceptionally if the attempt fails.
    • isConnected

      public boolean isConnected()
      Description copied from interface: Connection
      Indicates whether the connection has been successfully established and is active.
      Specified by:
      isConnected in interface Connection
      Returns:
      true if the connection is active, false otherwise.
    • getPipeline

      public Pipeline getPipeline()
      Description copied from interface: Connection
      Retrieves the associated Pipeline for this connection.
      Specified by:
      getPipeline in interface Connection
      Returns:
      the Pipeline instance used by this connection.
    • getNextSerial

      public DBusUInt32 getNextSerial()
      Description copied from interface: Connection
      Generates and returns the next unique serial number for outbound messages.

      Serial numbers are used to correlate requests and replies and are unique per connection.

      Specified by:
      getNextSerial in interface Connection
      Returns:
      a unique DBusUInt32 serial number for an OutboundMessage.
    • sendRequest

      public CompletionStage<InboundMessage> sendRequest(OutboundMessage msg)
      Description copied from interface: Connection
      Sends the given OutboundMessage over this connection, bypassing the pipeline.

      This method is intended for simple request-response interactions where no additional pipeline-based processing is needed. The returned CompletionStage is completed directly with the corresponding InboundMessage response or exceptionally if an error occurs.

      Note: Use this method only for straightforward communication scenarios that do not require handler involvement or advanced message routing.

      Specified by:
      sendRequest in interface Connection
      Parameters:
      msg - the outbound message to send.
      Returns:
      a CompletionStage that completes with the corresponding inbound response message, or fails exceptionally on error.
    • sendAndRouteResponse

      public void sendAndRouteResponse(OutboundMessage msg, CompletionStage<Void> future)
      Description copied from interface: Connection
      Sends the given OutboundMessage over the connection and completes the provided future when the message has been written to the D-Bus transport.

      The outbound message is transmitted directly over the connection and does not pass through the outbound pipeline. However, the corresponding InboundMessage response will be delivered through the pipeline, allowing it to be processed by registered InboundHandlers.

      This method is intended for scenarios where custom or advanced processing of responses is needed, while keeping message transmission efficient.

      Specified by:
      sendAndRouteResponse in interface Connection
      Parameters:
      msg - the outbound message to send.
      future - the CompletionStage to complete once the message is written or if an error occurs.
    • getConfig

      public ConnectionConfig getConfig()
      Description copied from interface: Connection
      Retrieves the configuration for this connection.
      Specified by:
      getConfig in interface Connection
      Returns:
      the ConnectionConfig instance used by this connection.
    • getState

      public ConnectionState getState()
      Description copied from interface: Connection
      Gets the current connection state.
      Specified by:
      getState in interface Connection
      Returns:
      the current ConnectionState
    • addConnectionEventListener

      public void addConnectionEventListener(ConnectionEventListener listener)
      Description copied from interface: Connection
      Adds a connection event listener to receive notifications about connection events.
      Specified by:
      addConnectionEventListener in interface Connection
      Parameters:
      listener - the listener to add
    • removeConnectionEventListener

      public void removeConnectionEventListener(ConnectionEventListener listener)
      Description copied from interface: Connection
      Removes a connection event listener.
      Specified by:
      removeConnectionEventListener in interface Connection
      Parameters:
      listener - the listener to remove
    • triggerHealthCheck

      public CompletionStage<Void> triggerHealthCheck()
      Description copied from interface: Connection
      Manually triggers a health check if health monitoring is enabled.
      Specified by:
      triggerHealthCheck in interface Connection
      Returns:
      a CompletionStage that completes when the health check is triggered
    • getReconnectAttemptCount

      public int getReconnectAttemptCount()
      Description copied from interface: Connection
      Gets the current number of reconnection attempts.
      Specified by:
      getReconnectAttemptCount in interface Connection
      Returns:
      the current reconnection attempt count
    • cancelReconnection

      public void cancelReconnection()
      Description copied from interface: Connection
      Cancels any pending reconnection attempts.
      Specified by:
      cancelReconnection in interface Connection
    • resetReconnectionState

      public void resetReconnectionState()
      Description copied from interface: Connection
      Resets the reconnection state, clearing attempt count and timers.
      Specified by:
      resetReconnectionState in interface Connection
    • close

      public void close()
      Specified by:
      close in interface AutoCloseable
    • setMethodCallResponse

      public final void setMethodCallResponse(String interfaceName, String methodName, Function<OutboundMessage,InboundMessage> responseFunction)
      Sets a response handler for method calls to a specific interface and method.
      Parameters:
      interfaceName - the D-Bus interface name
      methodName - the method name
      responseFunction - function to generate the response
    • wasMethodCalled

      public boolean wasMethodCalled(String interfaceName, String methodName)
      Checks if a method call was made to the specified interface and method.
      Parameters:
      interfaceName - the D-Bus interface name
      methodName - the method name
      Returns:
      true if the method was called
    • getMethodCallCount

      public int getMethodCallCount(String interfaceName, String methodName)
      Returns the number of times a method was called.
      Parameters:
      interfaceName - the D-Bus interface name
      methodName - the method name
      Returns:
      the number of times the method was called
    • getSentMessages

      public List<OutboundMessage> getSentMessages()
      Returns all messages sent through this connection.
      Returns:
      a list of sent messages (safe to modify)
    • getSentMessages

      public List<OutboundMessage> getSentMessages(Predicate<OutboundMessage> predicate)
      Returns all messages sent through this connection that match the given predicate.
      Parameters:
      predicate - the predicate to filter messages
      Returns:
      a list of matching messages
    • getMethodCalls

      public List<OutboundMethodCall> getMethodCalls(String interfaceName)
      Returns all method calls sent to a specific interface.
      Parameters:
      interfaceName - the D-Bus interface name
      Returns:
      a list of method calls to the interface
    • getConnectionEvents

      public List<ConnectionEvent> getConnectionEvents()
      Returns all connection events that have occurred.
      Returns:
      a list of connection events (safe to modify)
    • waitForEvent

      public boolean waitForEvent(ConnectionEventType eventType, long timeout, TimeUnit unit) throws InterruptedException
      Waits for a specific connection event to occur.
      Parameters:
      eventType - the type of event to wait for
      timeout - the maximum time to wait
      unit - the time unit of the timeout argument
      Returns:
      true if the event occurred, false if timeout
      Throws:
      InterruptedException - if the current thread is interrupted
    • clearCaptures

      public void clearCaptures()
      Clears all captured messages and events.
    • simulateConnectionFailure

      public void simulateConnectionFailure()
      Simulates a connection failure by transitioning to FAILED state.
    • simulateReconnection

      public void simulateReconnection()
      Simulates a reconnection attempt.
    • successResponse

      public static Function<OutboundMessage,InboundMessage> successResponse(List<DBusType> body)
      Creates a success response with the given body.
      Parameters:
      body - the response body
      Returns:
      a function that creates a success response
    • errorResponse

      public static Function<OutboundMessage,InboundMessage> errorResponse(String errorName, String errorMessage)
      Creates an error response with the given error name and message.
      Parameters:
      errorName - the D-Bus error name
      errorMessage - the error message
      Returns:
      a function that creates an error response