2 * ========================LICENSE_START=================================
5 * Copyright (C) 2024: OpenInfra Foundation Europe
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ========================LICENSE_END===================================
21 package com.demo.consumer;
23 import com.demo.consumer.consumer.SimpleConsumer;
24 import com.demo.consumer.messages.KafkaMessageHandler;
25 import com.demo.consumer.messages.PropertiesHelper;
27 import org.apache.kafka.clients.consumer.KafkaConsumer;
28 import org.junit.jupiter.api.AfterEach;
29 import org.junit.jupiter.api.BeforeEach;
30 import org.junit.jupiter.api.Test;
31 import org.mockito.InjectMocks;
32 import org.mockito.Mock;
33 import org.mockito.MockedStatic;
34 import org.mockito.Mockito;
35 import org.mockito.MockitoAnnotations;
37 import java.time.Duration;
39 import java.util.Properties;
41 import static org.mockito.Mockito.*;
43 class SimpleConsumerTest {
45 private static final long TIME_OUT_MS = 1000;
48 private KafkaConsumer<String, String> kafkaConsumer;
51 private SimpleConsumer simpleConsumer;
53 private AutoCloseable closable;
56 void setUp() throws Exception {
57 closable = MockitoAnnotations.openMocks(this);
61 void tearDown() throws Exception {
66 void testRun() throws Exception {
67 // Mocking the properties object returned by PropertiesHelper.getProperties()
68 Properties properties = new Properties();
69 properties.setProperty("bootstrap.servers", "localhost:9092");
70 properties.setProperty("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
71 properties.setProperty("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
73 // Mocking PropertiesHelper.getProperties() to return the mocked Properties object
74 try (MockedStatic<PropertiesHelper> propertiesHelperMockedStatic = Mockito.mockStatic(PropertiesHelper.class)) {
75 propertiesHelperMockedStatic.when(PropertiesHelper::getProperties).thenReturn(properties);
77 String topicName = "testTopic";
78 int numberOfMessages = 10;
79 KafkaMessageHandler callback = mock(KafkaMessageHandler.class);
81 simpleConsumer.run(topicName, numberOfMessages, callback);
82 verify(kafkaConsumer, times(0)).poll(Duration.ofMillis(TIME_OUT_MS));