eclipse / microprofile-reactive-messaging

Apache License 2.0
60 stars 37 forks source link

Unable use mockito to verify if Emitter::send() was called with the correct parameter #165

Open shyamsathyanathan opened 7 months ago

shyamsathyanathan commented 7 months ago

How to replicate

I have simple Kafka Producer like so

@ApplicationScoped
public class CustomizationProducer {

  Emitter<KafkaRecord<String, MyObject>> emitter;

  @Inject
  @Channel("customized-feed")
  public CustomizationProducer(Emitter<KafkaRecord<String, MyObject>> emitter) {
    this.emitter = emitter;
  }

  public void produce(MyObject data, String partitionKey) {
    KafkaRecord<String, MyObject> record = KafkaRecord.of(partitionKey, data);
    Message<KafkaRecord<String, MyObject>> message = Message.of(record);
    emitter.send(message);
  }
}

I would like to test this class using Mockito like so

public class CustomizationProducerTest {

  private CustomizationProducer customizationProducer;
  private Emitter<KafkaRecord<String, MyObject>> mockEmitter;

  @BeforeEach
  void setup() {
    mockEmitter = mock(Emitter.class);
    customizationProducer = new CustomizationProducer(mockEmitter);
  }

  @Test
  void shouldSendCustomizedFeedWithPartitionKey() {
    // Arrange
    var myObject = MockDataUtil.buildMyObject();
    var partitionKey = "xyz";
    var kafkaRecord = KafkaRecord.of(partitionKey, myObject);
    var expectedFeed = Message.of(kafkaRecord);

    // Act
    customizationProducer.produce(myObject, partitionKey);

    // Assert
    verify(mockEmitter).send(eq(expectedFeed));  <-- This fails because Message does not implement equals method correctly
  }

}

This test fails with the following stacktrace

Argument(s) are different! Wanted:
emitter.send(
    org.eclipse.microprofile.reactive.messaging.Message$$Lambda$494/0x000000012d2794a8@393881f0
);
-> at some.package.CustomizationProducerTest.shouldSendCustomizedFeedWithPartitionKey(CustomizationProducerTest.java:39)
Actual invocations have different arguments:
emitter.send(
    org.eclipse.microprofile.reactive.messaging.Message$$Lambda$494/0x000000012d2794a8@4af46df3
);

As you can see, the test is failing because the equals method is not properly implemented in Message