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 class
Builder for creating DummyConnection instances with custom configuration. -
Method Summary
Modifier and TypeMethodDescriptionvoid
Adds a connection event listener to receive notifications about connection events.static DummyConnection.Builder
builder()
Creates a new builder for configuring a DummyConnection.void
Cancels any pending reconnection attempts.void
Clears all captured messages and events.void
close()
connect()
Initiates a connection to a D-Bus instance.static DummyConnection
create()
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.int
getMethodCallCount
(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 associatedPipeline
for this connection.int
Gets 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.boolean
Indicates whether the connection has been successfully established and is active.void
Removes a connection event listener.void
Resets the reconnection state, clearing attempt count and timers.void
sendAndRouteResponse
(OutboundMessage msg, CompletionStage<Void> future) Sends the givenOutboundMessage
over the connection and completes the provided future when the message has been written to the D-Bus transport.Sends the givenOutboundMessage
over this connection, bypassing the pipeline.final void
setMethodCallResponse
(String interfaceName, String methodName, Function<OutboundMessage, InboundMessage> responseFunction) Sets a response handler for method calls to a specific interface and method.void
Simulates a connection failure by transitioning to FAILED state.void
Simulates 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.boolean
waitForEvent
(ConnectionEventType eventType, long timeout, TimeUnit unit) Waits for a specific connection event to occur.boolean
wasMethodCalled
(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:Connection
Initiates a connection to a D-Bus instance.- Specified by:
connect
in interfaceConnection
- 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 interfaceConnection
- Returns:
true
if the connection is active,false
otherwise.
-
getPipeline
Description copied from interface:Connection
Retrieves the associatedPipeline
for this connection.- Specified by:
getPipeline
in interfaceConnection
- Returns:
- the
Pipeline
instance used by this connection.
-
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 interfaceConnection
- Returns:
- a unique
DBusUInt32
serial number for anOutboundMessage
.
-
sendRequest
Description copied from interface:Connection
Sends the givenOutboundMessage
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 correspondingInboundMessage
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 interfaceConnection
- Parameters:
msg
- the outbound message to send.- Returns:
- a
CompletionStage
that completes with the corresponding inbound response message, or fails exceptionally on error.
-
sendAndRouteResponse
Description copied from interface:Connection
Sends the givenOutboundMessage
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 registeredInboundHandler
s.This method is intended for scenarios where custom or advanced processing of responses is needed, while keeping message transmission efficient.
- Specified by:
sendAndRouteResponse
in interfaceConnection
- Parameters:
msg
- the outbound message to send.future
- theCompletionStage
to complete once the message is written or if an error occurs.
-
getConfig
Description copied from interface:Connection
Retrieves the configuration for this connection.- Specified by:
getConfig
in interfaceConnection
- Returns:
- the
ConnectionConfig
instance used by this connection.
-
getState
Description copied from interface:Connection
Gets the current connection state.- Specified by:
getState
in interfaceConnection
- Returns:
- the current
ConnectionState
-
addConnectionEventListener
Description copied from interface:Connection
Adds a connection event listener to receive notifications about connection events.- Specified by:
addConnectionEventListener
in interfaceConnection
- Parameters:
listener
- the listener to add
-
removeConnectionEventListener
Description copied from interface:Connection
Removes a connection event listener.- Specified by:
removeConnectionEventListener
in interfaceConnection
- Parameters:
listener
- the listener to remove
-
triggerHealthCheck
Description copied from interface:Connection
Manually triggers a health check if health monitoring is enabled.- Specified by:
triggerHealthCheck
in interfaceConnection
- 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 interfaceConnection
- Returns:
- the current reconnection attempt count
-
cancelReconnection
public void cancelReconnection()Description copied from interface:Connection
Cancels any pending reconnection attempts.- Specified by:
cancelReconnection
in interfaceConnection
-
resetReconnectionState
public void resetReconnectionState()Description copied from interface:Connection
Resets the reconnection state, clearing attempt count and timers.- Specified by:
resetReconnectionState
in interfaceConnection
-
close
public void close()- Specified by:
close
in 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
-