最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

spring - How to populate setter getter methods in a class annotated with @Configuration in Junit Test case - Stack Overflow

programmeradmin3浏览0评论

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");
    

  }
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论