Class MockConsumer<K,V>
java.lang.Object
org.apache.kafka.clients.consumer.MockConsumer<K,V>
- All Implemented Interfaces:
Closeable, AutoCloseable, Consumer<K,V>
A mock of the
Consumer interface you can use for testing code that uses Kafka. This class is not
threadsafe . However, you can use the schedulePollTask(Runnable) method to write multithreaded tests
where a driver thread waits for poll(Duration) to be called by a background thread and then can safely perform
operations during a callback.-
Constructor Summary
ConstructorsConstructorDescriptionMockConsumer(String offsetResetStrategy) A mock consumer is instantiated by providing ConsumerConfig.AUTO_OFFSET_RESET_CONFIG value as the input.MockConsumer(OffsetResetStrategy offsetResetStrategy) Deprecated.Since 4.0. -
Method Summary
Modifier and TypeMethodDescriptionReturns the metrics registered viaregisterMetricForSubscription(KafkaMetric).voidaddRecord(ConsumerRecord<K, V> record) Adds a record to be returned whenpoll(Duration)is called.voidassign(Collection<TopicPartition> partitions) beginningOffsets(Collection<TopicPartition> partitions) beginningOffsets(Collection<TopicPartition> partitions, Duration timeout) clientInstanceId(Duration timeout) voidclose()voidDeprecated.voidclose(CloseOptions option) booleanclosed()Returns whether this consumer has been closed.voidvoidcommitAsync(Map<TopicPartition, OffsetAndMetadata> offsets, OffsetCommitCallback callback) voidcommitAsync(OffsetCommitCallback callback) voidvoidcommitSync(Duration timeout) voidcommitSync(Map<TopicPartition, OffsetAndMetadata> offsets) voidcommitSync(Map<TopicPartition, OffsetAndMetadata> offsets, Duration timeout) committed(Set<TopicPartition> partitions) committed(Set<TopicPartition> partitions, Duration timeout) currentLag(TopicPartition topicPartition) voidDisables telemetry for this mock consumer.endOffsets(Collection<TopicPartition> partitions) endOffsets(Collection<TopicPartition> partitions, Duration timeout) voidvoidenforceRebalance(String reason) voidinjectTimeoutException(int injectTimeoutExceptionCounter) Returns the timeout used in the lastpoll(Duration)call.listTopics(Duration timeout) voidlosePartitions(Collection<TopicPartition> partitionsLost) Simulates a partition loss event.Map<MetricName, ? extends Metric> metrics()offsetsForTimes(Map<TopicPartition, Long> timestampsToSearch) offsetsForTimes(Map<TopicPartition, Long> timestampsToSearch, Duration timeout) partitionsFor(String topic) partitionsFor(String topic, Duration timeout) voidpause(Collection<TopicPartition> partitions) paused()longposition(TopicPartition partition) longposition(TopicPartition partition, Duration timeout) voidrebalance(Collection<TopicPartition> newAssignment) Simulate a rebalance event.voidvoidResets the rebalance flag set byenforceRebalance().voidresume(Collection<TopicPartition> partitions) voidSchedules a no-op task to be executed during a poll invocation.voidschedulePollTask(Runnable task) Schedule a task to be executed during a poll().voidseek(TopicPartition partition, long offset) voidseek(TopicPartition partition, OffsetAndMetadata offsetAndMetadata) voidseekToBeginning(Collection<TopicPartition> partitions) voidseekToEnd(Collection<TopicPartition> partitions) voidsetClientInstanceId(Uuid instanceId) Sets the client instance ID for this mock consumer.voidsetMaxPollRecords(long maxPollRecords) Sets the maximum number of records returned in a single call topoll(Duration).voidsetOffsetsException(KafkaException exception) Sets an exception to throw when offset-related methods are called.voidsetPollException(KafkaException exception) Sets an exception to throw whenpoll(Duration)is called.booleanReturns whether a rebalance has been triggered viaenforceRebalance().voidsubscribe(Collection<String> topics) voidsubscribe(Collection<String> topics, ConsumerRebalanceListener listener) voidvoidsubscribe(Pattern pattern, ConsumerRebalanceListener listener) voidsubscribe(SubscriptionPattern pattern) voidsubscribe(SubscriptionPattern pattern, ConsumerRebalanceListener listener) voidvoidvoidupdateBeginningOffsets(Map<TopicPartition, Long> newOffsets) Updates the beginning offsets for the specified partitions.voidupdateDurationOffsets(Map<TopicPartition, Long> newOffsets) Updates the duration-based reset offsets for the specified partitions.voidupdateEndOffsets(Map<TopicPartition, Long> newOffsets) Updates the end offsets for the specified partitions.voidupdatePartitions(String topic, List<PartitionInfo> partitions) Updates the partition information for the specified topic.voidwakeup()
-
Constructor Details
-
MockConsumer
Deprecated.Since 4.0. UseMockConsumer(String)instead. -
MockConsumer
A mock consumer is instantiated by providing ConsumerConfig.AUTO_OFFSET_RESET_CONFIG value as the input.- Parameters:
offsetResetStrategy- the offset reset strategy to use
-
-
Method Details
-
assignment
- Specified by:
assignmentin interfaceConsumer<K,V> - See Also:
-
rebalance
Simulate a rebalance event. -
losePartitions
Simulates a partition loss event. CallsConsumerRebalanceListener.onPartitionsLost(Collection)for the specified partitions and removes them from the current assignment. Unlikerebalance(Collection), which callsConsumerRebalanceListener.onPartitionsRevoked(Collection), this method models the case where the consumer loses partitions without a graceful revoke..Only records belonging to the lost partitions are cleared; records for retained partitions are unaffected.
- Parameters:
partitionsLost- the partitions to lose; all must be currently assigned- Throws:
IllegalStateException- if any partition is not currently assigned
-
subscription
-
subscribe
-
subscribe
-
subscribe
-
subscribe
-
subscribe
-
subscribe
-
registerMetricForSubscription
- Specified by:
registerMetricForSubscriptionin interfaceConsumer<K,V> - See Also:
-
unregisterMetricFromSubscription
- Specified by:
unregisterMetricFromSubscriptionin interfaceConsumer<K,V> - See Also:
-
assign
-
unsubscribe
public void unsubscribe()- Specified by:
unsubscribein interfaceConsumer<K,V> - See Also:
-
poll
-
addRecord
Adds a record to be returned whenpoll(Duration)is called.- Parameters:
record- the record to add- Throws:
IllegalStateException- if the partition is not assigned to the consumer
-
setMaxPollRecords
public void setMaxPollRecords(long maxPollRecords) Sets the maximum number of records returned in a single call topoll(Duration).- Parameters:
maxPollRecords- the max.poll.records.
-
setPollException
Sets an exception to throw whenpoll(Duration)is called.- Parameters:
exception- the exception to throw
-
setOffsetsException
Sets an exception to throw when offset-related methods are called.- Parameters:
exception- the exception to throw
-
commitAsync
public void commitAsync(Map<TopicPartition, OffsetAndMetadata> offsets, OffsetCommitCallback callback) - Specified by:
commitAsyncin interfaceConsumer<K,V> - See Also:
-
commitSync
- Specified by:
commitSyncin interfaceConsumer<K,V> - See Also:
-
commitAsync
public void commitAsync()- Specified by:
commitAsyncin interfaceConsumer<K,V> - See Also:
-
commitAsync
- Specified by:
commitAsyncin interfaceConsumer<K,V> - See Also:
-
commitSync
public void commitSync()- Specified by:
commitSyncin interfaceConsumer<K,V> - See Also:
-
commitSync
- Specified by:
commitSyncin interfaceConsumer<K,V> - See Also:
-
commitSync
- Specified by:
commitSyncin interfaceConsumer<K,V> - See Also:
-
seek
-
seek
-
committed
-
committed
public Map<TopicPartition, OffsetAndMetadata> committed(Set<TopicPartition> partitions, Duration timeout) -
position
-
position
-
seekToBeginning
- Specified by:
seekToBeginningin interfaceConsumer<K,V> - See Also:
-
updateBeginningOffsets
Updates the beginning offsets for the specified partitions.- Parameters:
newOffsets- the beginning offsets to set
-
seekToEnd
-
updateEndOffsets
Updates the end offsets for the specified partitions.- Parameters:
newOffsets- the end offsets to set
-
updateDurationOffsets
Updates the duration-based reset offsets for the specified partitions.- Parameters:
newOffsets- the duration offsets to set
-
disableTelemetry
public void disableTelemetry()Disables telemetry for this mock consumer. -
injectTimeoutException
public void injectTimeoutException(int injectTimeoutExceptionCounter) - Parameters:
injectTimeoutExceptionCounter- use -1 for infinite
-
setClientInstanceId
Sets the client instance ID for this mock consumer.- Parameters:
instanceId- the client instance ID
-
clientInstanceId
Description copied from interface:Consumer- Specified by:
clientInstanceIdin interfaceConsumer<K,V>
-
metrics
-
partitionsFor
- Specified by:
partitionsForin interfaceConsumer<K,V> - See Also:
-
listTopics
- Specified by:
listTopicsin interfaceConsumer<K,V> - See Also:
-
updatePartitions
Updates the partition information for the specified topic.- Parameters:
topic- the topic to updatepartitions- the partition information
-
pause
-
resume
-
offsetsForTimes
public Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(Map<TopicPartition, Long> timestampsToSearch) - Specified by:
offsetsForTimesin interfaceConsumer<K,V> - See Also:
-
beginningOffsets
- Specified by:
beginningOffsetsin interfaceConsumer<K,V> - See Also:
-
endOffsets
- Specified by:
endOffsetsin interfaceConsumer<K,V> - See Also:
-
close
-
close
-
closed
public boolean closed()Returns whether this consumer has been closed.- Returns:
- true if closed, false otherwise
-
wakeup
-
close
-
schedulePollTask
Schedule a task to be executed during a poll(). One enqueued task will be executed perpoll(Duration)invocation. You can use this repeatedly to mock out multiple responses to poll invocations.- Parameters:
task- the task to be executed
-
scheduleNopPollTask
public void scheduleNopPollTask()Schedules a no-op task to be executed during a poll invocation. -
paused
-
partitionsFor
- Specified by:
partitionsForin interfaceConsumer<K,V> - See Also:
-
listTopics
- Specified by:
listTopicsin interfaceConsumer<K,V> - See Also:
-
offsetsForTimes
public Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(Map<TopicPartition, Long> timestampsToSearch, Duration timeout) - Specified by:
offsetsForTimesin interfaceConsumer<K,V> - See Also:
-
beginningOffsets
public Map<TopicPartition, Long> beginningOffsets(Collection<TopicPartition> partitions, Duration timeout) - Specified by:
beginningOffsetsin interfaceConsumer<K,V> - See Also:
-
endOffsets
public Map<TopicPartition, Long> endOffsets(Collection<TopicPartition> partitions, Duration timeout) - Specified by:
endOffsetsin interfaceConsumer<K,V> - See Also:
-
currentLag
- Specified by:
currentLagin interfaceConsumer<K,V> - See Also:
-
groupMetadata
- Specified by:
groupMetadatain interfaceConsumer<K,V> - See Also:
-
enforceRebalance
public void enforceRebalance()- Specified by:
enforceRebalancein interfaceConsumer<K,V> - See Also:
-
enforceRebalance
- Specified by:
enforceRebalancein interfaceConsumer<K,V> - See Also:
-
shouldRebalance
public boolean shouldRebalance()Returns whether a rebalance has been triggered viaenforceRebalance().- Returns:
- true if rebalance is pending, false otherwise
-
resetShouldRebalance
public void resetShouldRebalance()Resets the rebalance flag set byenforceRebalance(). -
lastPollTimeout
Returns the timeout used in the lastpoll(Duration)call.- Returns:
- the last poll timeout, or null if poll has not been called
-
addedMetrics
Returns the metrics registered viaregisterMetricForSubscription(KafkaMetric).- Returns:
- an unmodifiable list of added metrics
-