Skip to content

Instantly share code, notes, and snippets.

@kasramp
Last active April 7, 2021 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kasramp/6db4704ca39031f8c0b522db03dcaef2 to your computer and use it in GitHub Desktop.
Save kasramp/6db4704ca39031f8c0b522db03dcaef2 to your computer and use it in GitHub Desktop.
@EmbeddedKafka
@SpringBootTest(properties = "spring.kafka.bootstrap-servers=${spring.embedded.kafka.brokers}")
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class UserKafkaProducerTest {
private BlockingQueue<ConsumerRecord<String, String>> records;
private KafkaMessageListenerContainer<String, String> container;
@Autowired
private EmbeddedKafkaBroker embeddedKafkaBroker;
@Autowired
private UserKafkaProducer producer;
@Autowired
private ObjectMapper objectMapper;
@BeforeAll
void setUp() {
DefaultKafkaConsumerFactory<String, String> consumerFactory = new DefaultKafkaConsumerFactory<>(getConsumerProperties());
ContainerProperties containerProperties = new ContainerProperties("com.madadipouya.kafka.user");
container = new KafkaMessageListenerContainer<>(consumerFactory, containerProperties);
records = new LinkedBlockingQueue<>();
container.setupMessageListener((MessageListener<String, String>) records::add);
container.start();
ContainerTestUtils.waitForAssignment(container, embeddedKafkaBroker.getPartitionsPerTopic());
}
private Map<String, Object> getConsumerProperties() {
return Map.of(
ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, embeddedKafkaBroker.getBrokersAsString(),
ConsumerConfig.GROUP_ID_CONFIG, "consumer",
ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true",
ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "10",
ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "60000",
ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class,
ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class,
ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
}
@AfterAll
void tearDown() {
container.stop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment