Class MockProducer<K,V>
java.lang.Object
org.apache.kafka.clients.producer.MockProducer<K,V>
- All Implemented Interfaces:
Closeable,AutoCloseable,Producer<K,V>
A mock of the producer interface you can use for testing code that uses Kafka.
By default this mock will synchronously complete each send call successfully. However it can be configured to allow the user to control the completion of the call and supply an optional error for the producer to throw.
-
Field Summary
FieldsModifier and TypeFieldDescriptionException to throw whenabortTransaction()is calledException to throw whenbeginTransaction()is calledException to throw whenclose()orclose(Duration)is calledException to throw whencommitTransaction()is calledException to throw whenflush()is calledException to throw wheninitTransactions()is calledException to throw whenpartitionsFor(String)is calledException to throw whensend(ProducerRecord)orsend(ProducerRecord, Callback)is calledException to throw whensendOffsetsToTransaction(Map, ConsumerGroupMetadata)is called -
Constructor Summary
ConstructorsConstructorDescriptionCreate a new mock producer with invented metadata.MockProducer(boolean autoComplete, Partitioner partitioner, Serializer<K> keySerializer, Serializer<V> valueSerializer) Create a new mock producer with invented metadata the given autoComplete setting, partitioner and key\value serializers.MockProducer(Cluster cluster, boolean autoComplete, Partitioner partitioner, Serializer<K> keySerializer, Serializer<V> valueSerializer) Create a mock producer -
Method Summary
Modifier and TypeMethodDescriptionvoidGets the list of metrics that have been registered for subscription.voidvoidclear()Clear the stored history of sent records, consumer group offsetsclientInstanceId(Duration timeout) voidclose()voidbooleanclosed()Checks whether this mock producer has been closed.longGets the total number of transactions committed by this mock producer.voidbooleanComplete the earliest uncompleted call successfully.Get the list of committed consumer group offsets since the last call toclear()voidDisables telemetry for this mock producer for testing purposes.booleanComplete the earliest uncompleted call with the given error.voidFences this mock producer, causing it to throwProducerFencedExceptionon subsequent transactional operations.voidflush()booleanflushed()Checks whether all sent records have been completed (no pending completions).List<ProducerRecord<K,V>> history()Get the list of sent records since the last call toclear()voidvoidinjectTimeoutException(int injectTimeoutExceptionCounter) Injects timeout exceptions intoclientInstanceId(Duration)calls for testing purposes.metrics()partitionsFor(String topic) voidsend(ProducerRecord<K, V> record) Adds the record to the list of sent records.send(ProducerRecord<K, V> record, Callback callback) Adds the record to the list of sent records.voidsendOffsetsToTransaction(Map<TopicPartition, OffsetAndMetadata> offsets, ConsumerGroupMetadata groupMetadata) booleanChecks whether offsets have been sent to the current transaction.voidsetClientInstanceId(Uuid instanceId) Sets the client instance ID for this mock producer.voidsetMockMetrics(MetricName name, Metric metric) Set a mock metric for testing purposebooleanChecks whether the current transaction has been aborted.booleanChecks whether the current transaction has been committed.booleanChecks whether a transaction is currently in progress.booleanChecks whether transactions have been initialized for this mock producer.Gets the consumer group offsets sent in the current transaction that have not yet been committed.List<ProducerRecord<K,V>> Gets the list of records sent in the current transaction that have not yet been committed.void
-
Field Details
-
initTransactionException
Exception to throw wheninitTransactions()is called -
beginTransactionException
Exception to throw whenbeginTransaction()is called -
sendOffsetsToTransactionException
Exception to throw whensendOffsetsToTransaction(Map, ConsumerGroupMetadata)is called -
commitTransactionException
Exception to throw whencommitTransaction()is called -
abortTransactionException
Exception to throw whenabortTransaction()is called -
sendException
Exception to throw whensend(ProducerRecord)orsend(ProducerRecord, Callback)is called -
flushException
Exception to throw whenflush()is called -
partitionsForException
Exception to throw whenpartitionsFor(String)is called -
closeException
Exception to throw whenclose()orclose(Duration)is called
-
-
Constructor Details
-
MockProducer
public MockProducer(Cluster cluster, boolean autoComplete, Partitioner partitioner, Serializer<K> keySerializer, Serializer<V> valueSerializer) Create a mock producer- Parameters:
cluster- The cluster holding metadata for this producerautoComplete- If true automatically complete all requests successfully and execute the callback. Otherwise the user must callcompleteNext()orerrorNext(RuntimeException)aftersend()to complete the call and unblock theFuture<RecordMetadata>that is returned.partitioner- The partition strategykeySerializer- The serializer for key that implementsSerializer.valueSerializer- The serializer for value that implementsSerializer.
-
MockProducer
public MockProducer(boolean autoComplete, Partitioner partitioner, Serializer<K> keySerializer, Serializer<V> valueSerializer) Create a new mock producer with invented metadata the given autoComplete setting, partitioner and key\value serializers. Equivalent tonew MockProducer(Cluster.empty(), autoComplete, partitioner, keySerializer, valueSerializer) -
MockProducer
public MockProducer()Create a new mock producer with invented metadata. Equivalent tonew MockProducer(Cluster.empty(), false, null, null, null)
-
-
Method Details
-
initTransactions
public void initTransactions()Description copied from interface:Producer- Specified by:
initTransactionsin interfaceProducer<K,V>
-
beginTransaction
Description copied from interface:Producer- Specified by:
beginTransactionin interfaceProducer<K,V> - Throws:
ProducerFencedException
-
sendOffsetsToTransaction
public void sendOffsetsToTransaction(Map<TopicPartition, OffsetAndMetadata> offsets, ConsumerGroupMetadata groupMetadata) throws ProducerFencedExceptionDescription copied from interface:Producer- Specified by:
sendOffsetsToTransactionin interfaceProducer<K,V> - Throws:
ProducerFencedException
-
commitTransaction
Description copied from interface:Producer- Specified by:
commitTransactionin interfaceProducer<K,V> - Throws:
ProducerFencedException
-
abortTransaction
Description copied from interface:Producer- Specified by:
abortTransactionin interfaceProducer<K,V> - Throws:
ProducerFencedException
-
send
Adds the record to the list of sent records. TheRecordMetadatareturned will be immediately satisfied. -
send
Adds the record to the list of sent records. -
flush
public void flush()Description copied from interface:Producer -
partitionsFor
Description copied from interface:Producer- Specified by:
partitionsForin interfaceProducer<K,V>
-
disableTelemetry
public void disableTelemetry()Disables telemetry for this mock producer for testing purposes. -
injectTimeoutException
public void injectTimeoutException(int injectTimeoutExceptionCounter) Injects timeout exceptions intoclientInstanceId(Duration)calls for testing purposes.- Parameters:
injectTimeoutExceptionCounter- Number of times to inject timeout exceptions, or -1 for infinite
-
setClientInstanceId
Sets the client instance ID for this mock producer.- Parameters:
instanceId- The client instance ID to set
-
clientInstanceId
Description copied from interface:Producer- Specified by:
clientInstanceIdin interfaceProducer<K,V>
-
metrics
Description copied from interface:Producer -
setMockMetrics
Set a mock metric for testing purpose -
close
public void close()Description copied from interface:Producer -
close
Description copied from interface:Producer -
closed
public boolean closed()Checks whether this mock producer has been closed.- Returns:
trueif the producer has been closed,falseotherwise
-
fenceProducer
public void fenceProducer()Fences this mock producer, causing it to throwProducerFencedExceptionon subsequent transactional operations. -
transactionInitialized
public boolean transactionInitialized()Checks whether transactions have been initialized for this mock producer.- Returns:
trueif transactions have been initialized,falseotherwise
-
transactionInFlight
public boolean transactionInFlight()Checks whether a transaction is currently in progress.- Returns:
trueif a transaction is in progress,falseotherwise
-
transactionCommitted
public boolean transactionCommitted()Checks whether the current transaction has been committed.- Returns:
trueif the transaction was committed,falseotherwise
-
transactionAborted
public boolean transactionAborted()Checks whether the current transaction has been aborted.- Returns:
trueif the transaction was aborted,falseotherwise
-
flushed
public boolean flushed()Checks whether all sent records have been completed (no pending completions).- Returns:
trueif there are no pending completions,falseotherwise
-
sentOffsets
public boolean sentOffsets()Checks whether offsets have been sent to the current transaction.- Returns:
trueif offsets were sent in the current transaction,falseotherwise
-
commitCount
public long commitCount()Gets the total number of transactions committed by this mock producer.- Returns:
- The commit count
-
history
Get the list of sent records since the last call toclear() -
uncommittedRecords
Gets the list of records sent in the current transaction that have not yet been committed.- Returns:
- A list of uncommitted producer records
-
consumerGroupOffsetsHistory
Get the list of committed consumer group offsets since the last call toclear() -
uncommittedOffsets
Gets the consumer group offsets sent in the current transaction that have not yet been committed.- Returns:
- A map of consumer group IDs to their uncommitted offsets
-
clear
public void clear()Clear the stored history of sent records, consumer group offsets -
completeNext
public boolean completeNext()Complete the earliest uncompleted call successfully.- Returns:
- true if there was an uncompleted call to complete
-
errorNext
Complete the earliest uncompleted call with the given error.- Returns:
- true if there was an uncompleted call to complete
-
addedMetrics
Gets the list of metrics that have been registered for subscription.- Returns:
- An unmodifiable list of added metrics
-
registerMetricForSubscription
Description copied from interface:Producer- Specified by:
registerMetricForSubscriptionin interfaceProducer<K,V>
-
unregisterMetricFromSubscription
Description copied from interface:Producer- Specified by:
unregisterMetricFromSubscriptionin interfaceProducer<K,V>
-