use mockito to write Kafka producer unit test.
时间: 2024-05-03 13:19:07 浏览: 174
Sure, here's an example of how you can use Mockito to write a unit test for a Kafka producer:
```java
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Properties;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
public class KafkaProducerUnitTest {
@Mock
private KafkaProducer<String, String> kafkaProducer;
@InjectMocks
private KafkaService kafkaService = new KafkaService();
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testSendMessage() {
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
when(kafkaService.createProducer(props)).thenReturn(kafkaProducer);
String topic = "test-topic";
String message = "Hello, Kafka!";
kafkaService.sendMessage(topic, message);
verify(kafkaProducer, times(1)).send(new ProducerRecord<>(topic, message));
}
}
```
In this example, we have a `KafkaService` class that wraps the Kafka producer, and we want to test its `sendMessage` method. We use Mockito to mock the Kafka producer and inject it into the `KafkaService`, and then we use the `when` method to specify the behavior of the `createProducer` method.
In the test method, we call the `sendMessage` method with a topic and a message, and then we verify that the `send` method of the Kafka producer is called once with the correct arguments.
Note that you'll need to add the Mockito and Kafka dependencies to your project for this example to work.
阅读全文