testtt
testtt

Reputation: 11

Spring Testcontainers with kafka producer

I'm trying to integrate Testcontainers in my spring boot app. I'm using Kafka Container to allow sending Kafka messages. The main issue is that when I send message to kafka correctly, I would like to know what approach should be fine to validate if it was properly send. Because I don't want to include consumer part in my service in which is only producer.

I'm not mocking producer interface, so I'm not able to verify that method send was called. Thank you in advance

Upvotes: 0

Views: 944

Answers (1)

Artem Bilan
Artem Bilan

Reputation: 121462

You simple can create a KafkaTemplate in your unit test and use its receive() API: https://docs.spring.io/spring-kafka/reference/kafka/receiving-messages/template-receive.html. A ConsumerFactory must be provided into that KafkaTemplate:

/**
 * Set a consumer factory for receive operations.
 * @param consumerFactory the consumer factory.
 * @since 2.8
 */
public void setConsumerFactory(ConsumerFactory<K, V> consumerFactory) {

Another option is to use KafkaTestUtils.getOneRecord():

/**
 * Get a single record for the group from the topic/partition. Optionally, seeking to the current last record.
 * @param brokerAddresses the broker address(es).
 * @param group the group.
 * @param topic the topic.
 * @param partition the partition.
 * @param seekToLast true to fetch an existing last record, if present.
 * @param commit commit offset after polling or not.
 * @param timeout the timeout.
 * @return the record or null if no record received.
 * @since 2.9.3
 */
@Nullable
@SuppressWarnings({ "rawtypes", "unchecked" })
public static ConsumerRecord<?, ?> getOneRecord(String brokerAddresses, String group, String topic, int partition,
        boolean seekToLast, boolean commit, Duration timeout) {

However it doesn't sound like you use spring-kafka-test module in your project.

Upvotes: 0

Related Questions