Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Actually, there were zero interactions with this mock. Embedded Kafka Spring test

I'm trying to see if a method from Service class is invoked when the consumer consumes a message from Kafka topic but i'm getting the error that there is no zero interactions with the Mock. When the test is running it consumes the message and I can see on terminal that the service method is actually invoked (i tried with prints), but it is not passing the test.

My Consumer class:

@Component
public class Consumer {
  
    @Autowired
    private Service service;

    @KafkaListener(topics = "topic")
    public void consume(String message) { 
        service.add();
    }
}

The test:

@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
@DirtiesContext
@EmbeddedKafka(partitions = 1, brokerProperties = { "listeners=PLAINTEXT://localhost:9092", "port=9092" })
class ConsumerTest {

  @Mock( lenient = true)
  private Service service;

  @Autowired
  private KafkaTemplate<String, String> kafkaTemplate;

  @InjectMocks
  private Consumer consumer;

  @Test
  public void givenEmbeddedKafkaBroker_whenExistsTemperatureMessageInTopic_thenMessageReceivedByConsumerAndServiceInvoked() 
    throws Exception {

      String message = "Hello";

      kafkaTemplate.send("topic", message);

      Mockito.verify(service, times(1)).add();
  }
}
like image 852
kayla Avatar asked Nov 23 '25 11:11

kayla


1 Answers

I have similar issue, and solved by using the Spybean instead of the MockBean, maybe you can have a try to use the SpyBean, your code will be something like this:

class ConsumerTest {

@Autowired
private KafkaTemplate<String, String> kafkaTemplate;

@SpyBean
private Consumer consumer;
like image 128
Ray Avatar answered Nov 27 '25 00:11

Ray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!