How to migrate from Powermock wenNew withAnyArguments thenReturn to Mockito 5?

46 views Asked by At

Since I need to upgrade to JDK the following use of PowerMock I need to migrate to a newer version of Mockito which from what I understand now implements PowerMock's functionalities:

PowerMockito.whenNew(KafkaProducer.class).withAnyArguments().thenReturn(mockKafkaProducer);

I've read similar threads about the matter but I'm failing to understand this particular case, below the full code:

@RunWith(PowerMockRunner.class)
@PrepareForTest({KafkaClientFactory.class})
public class KafkaClientFactoryTest {


@Test
public void shouldCreateKafkaProducerClient() throws Exception {
    KafkaProducer<String, String> mockKafkaProducer = mock(KafkaProducer.class);
    PowerMockito.whenNew(KafkaProducer.class).withAnyArguments().thenReturn(mockKafkaProducer);

    String stringSerializer = "org.apache.kafka.common.serialization.StringSerializer";
    Properties kafkaProperties = new Properties();
    kafkaProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9093");
    kafkaProperties.put(ProducerConfig.ACKS_CONFIG, "all");
    kafkaProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, stringSerializer);
    kafkaProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, stringSerializer);
    kafkaProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, stringSerializer);

    KafkaProducer<String, String> kafkaProducer = KafkaClientFactory.createKafkaProducer(toKafkaConfig(kafkaProperties));

    assertEquals(kafkaProducer, mockKafkaProducer);
}
}
0

There are 0 answers