I have created a library using Spring to send message using Kafka Template. I am using the library in Spring boot application. The configuration fields are fetched from application.yml in Sprint boot appliacation. I am writing test case for library developed using Spring. When I run the test case in debug mode. It is taking me directly to KafkaProducerConfig->producerFactory() method. Where bootstrapServers is null. How to load the configuration from method annotated with @BeforeEach
KafkaProducerConfig.java
@ConfigurationProperties(prefix = "si-producer.kafka.configuration")
@Configuration
@Data
public class KafkaProducerConfig {
private String bootstrapServers;
@Bean("siProducerFactory")
ProducerFactory<String, String> producerFactory() throws FileNotFoundException {
Map<String, Object> props = new HashMap<>();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
return new DefaultKafkaProducerFactory<>(props);
}
@Bean("siKafkaTemplate")
KafkaTemplate<String, String> commonProducerKafkaTemplate() throws FileNotFoundException {
return new KafkaTemplate<>(producerFactory());
}
MessageProducerServiceImpl.java
@Service
public class MessageProducerServiceImpl {
@Autowired
@Qualifier("siKafkaTemplate")
private KafkaTemplate<String, String> kafkaTemplate;
@Value("${si-producer.kafka.configuration.topic}")
private String topic;
/**
* @param message
* @param trackingId
*/
@Override
public void sendMessage(String message) {
try {
kafkaTemplate.send(this.topic, message).whenComplete((result, throwable) -> {
if (throwable != null) {
log.info("Unable to send message: {} due to: {}", message, throwable.getMessage());
} else {
log.info("Sent message: {} with offset: {} and with partition: {}", message,
result.getRecordMetadata().offset(), result.getRecordMetadata().partition());
}
});
} catch (Exception e) {
log.info("Send Message failed due to: {}", e.getMessage());
}
}
}
MessageProducerServiceImplTest.java
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {KafkaProducerConfig.class})
@PropertySource("classpath:application.yml")
public class MessageProducerServiceImplTest {
@Autowired
private MessageProducerServiceImpl messageProducerServiceImpl;
Autowired
private KafkaProducerConfig kafkaProducerConfig;
@MockBean
private KafkaTemplate<String, String> kafkaTemplate;
@BeforeEach
void setUp() {
kafkaProducerConfig.setBootstrapServers("somebootstrapServer");
}
@Test
void sendMessageTest() throws Exception {
messageProducerServiceImpl.sendMessage("somemessage");
}
}