Class DummyConnection
- All Implemented Interfaces:
Connection,AutoCloseable
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
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classBuilder for creating DummyConnection instances with custom configuration. -
Method Summary
Modifier and TypeMethodDescriptionvoidAdds a connection event listener to receive notifications about connection events.static DummyConnection.Builderbuilder()Creates a new builder for configuring a DummyConnection.voidCancels any pending reconnection attempts.voidClears all captured messages and events.voidclose()connect()Initiates a connection to a D-Bus instance.static DummyConnectioncreate()Creates a simple DummyConnection with default configuration.static Function<OutboundMessage,InboundMessage> errorResponse(String errorName, String errorMessage) Creates an error response with the given error name and message.Retrieves the configuration for this connection.Returns all connection events that have occurred.intgetMethodCallCount(String interfaceName, String methodName) Returns the number of times a method was called.getMethodCalls(String interfaceName) Returns all method calls sent to a specific interface.Generates and returns the next unique serial number for outbound messages.Retrieves the associatedPipelinefor this connection.intGets the current number of reconnection attempts.Returns all messages sent through this connection.getSentMessages(Predicate<OutboundMessage> predicate) Returns all messages sent through this connection that match the given predicate.getState()Gets the current connection state.booleanIndicates whether the connection has been successfully established and is active.voidRemoves a connection event listener.voidResets the reconnection state, clearing attempt count and timers.voidsendAndRouteResponse(OutboundMessage msg, CompletionStage<Void> future) Sends the givenOutboundMessageover the connection and completes the provided future when the message has been written to the D-Bus transport.Sends the givenOutboundMessageover this connection, bypassing the pipeline.final voidsetMethodCallResponse(String interfaceName, String methodName, Function<OutboundMessage, InboundMessage> responseFunction) Sets a response handler for method calls to a specific interface and method.voidSimulates a connection failure by transitioning to FAILED state.voidSimulates a reconnection attempt.static Function<OutboundMessage,InboundMessage> successResponse(List<DBusType> body) Creates a success response with the given body.Manually triggers a health check if health monitoring is enabled.booleanwaitForEvent(ConnectionEventType eventType, long timeout, TimeUnit unit) Waits for a specific connection event to occur.booleanwasMethodCalled(String interfaceName, String methodName) Checks if a method call was made to the specified interface and method.
-
Method Details
-
builder
Creates a new builder for configuring a DummyConnection.- Returns:
- a new Builder instance
-
create
Creates a simple DummyConnection with default configuration.- Returns:
- a new DummyConnection instance ready for use
-
connect
Description copied from interface:ConnectionInitiates a connection to a D-Bus instance.- Specified by:
connectin interfaceConnection- Returns:
- a
CompletionStagethat completes when the connection is established, or exceptionally if the attempt fails.
-
isConnected
public boolean isConnected()Description copied from interface:ConnectionIndicates whether the connection has been successfully established and is active.- Specified by:
isConnectedin interfaceConnection- Returns:
trueif the connection is active,falseotherwise.
-
getPipeline
Description copied from interface:ConnectionRetrieves the associatedPipelinefor this connection.- Specified by:
getPipelinein interfaceConnection- Returns:
- the
Pipelineinstance used by this connection.
-
getNextSerial
Description copied from interface:ConnectionGenerates 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:
getNextSerialin interfaceConnection- Returns:
- a unique
DBusUInt32serial number for anOutboundMessage.
-
sendRequest
Description copied from interface:ConnectionSends the givenOutboundMessageover this connection, bypassing the pipeline.This method is intended for simple request-response interactions where no additional pipeline-based processing is needed. The returned
CompletionStageis completed directly with the correspondingInboundMessageresponse 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:
sendRequestin interfaceConnection- Parameters:
msg- the outbound message to send.- Returns:
- a
CompletionStagethat completes with the corresponding inbound response message, or fails exceptionally on error.
-
sendAndRouteResponse
Description copied from interface:ConnectionSends the givenOutboundMessageover 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
InboundMessageresponse will be delivered through the pipeline, allowing it to be processed by registeredInboundHandlers.This method is intended for scenarios where custom or advanced processing of responses is needed, while keeping message transmission efficient.
- Specified by:
sendAndRouteResponsein interfaceConnection- Parameters:
msg- the outbound message to send.future- theCompletionStageto complete once the message is written or if an error occurs.
-
getConfig
Description copied from interface:ConnectionRetrieves the configuration for this connection.- Specified by:
getConfigin interfaceConnection- Returns:
- the
ConnectionConfiginstance used by this connection.
-
getState
Description copied from interface:ConnectionGets the current connection state.- Specified by:
getStatein interfaceConnection- Returns:
- the current
ConnectionState
-
addConnectionEventListener
Description copied from interface:ConnectionAdds a connection event listener to receive notifications about connection events.- Specified by:
addConnectionEventListenerin interfaceConnection- Parameters:
listener- the listener to add
-
removeConnectionEventListener
Description copied from interface:ConnectionRemoves a connection event listener.- Specified by:
removeConnectionEventListenerin interfaceConnection- Parameters:
listener- the listener to remove
-
triggerHealthCheck
Description copied from interface:ConnectionManually triggers a health check if health monitoring is enabled.- Specified by:
triggerHealthCheckin interfaceConnection- Returns:
- a
CompletionStagethat completes when the health check is triggered
-
getReconnectAttemptCount
public int getReconnectAttemptCount()Description copied from interface:ConnectionGets the current number of reconnection attempts.- Specified by:
getReconnectAttemptCountin interfaceConnection- Returns:
- the current reconnection attempt count
-
cancelReconnection
public void cancelReconnection()Description copied from interface:ConnectionCancels any pending reconnection attempts.- Specified by:
cancelReconnectionin interfaceConnection
-
resetReconnectionState
public void resetReconnectionState()Description copied from interface:ConnectionResets the reconnection state, clearing attempt count and timers.- Specified by:
resetReconnectionStatein interfaceConnection
-
close
public void close()- Specified by:
closein interfaceAutoCloseable
-
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 namemethodName- the method nameresponseFunction- function to generate the response
-
wasMethodCalled
Checks if a method call was made to the specified interface and method.- Parameters:
interfaceName- the D-Bus interface namemethodName- the method name- Returns:
- true if the method was called
-
getMethodCallCount
Returns the number of times a method was called.- Parameters:
interfaceName- the D-Bus interface namemethodName- the method name- Returns:
- the number of times the method was called
-
getSentMessages
Returns all messages sent through this connection.- Returns:
- a list of sent messages (safe to modify)
-
getSentMessages
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
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
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 fortimeout- the maximum time to waitunit- 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
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 nameerrorMessage- the error message- Returns:
- a function that creates an error response
-