如何验证lambda函数Mockito

q7solyqu  于 2022-12-18  发布在  其他
关注(0)|答案(1)|浏览(272)

我正在尝试测试以下方法:

public void execute(Publisher<T> publisher) throws Exception {
    PublishStrategy<T> publishStrategy = publisher.getPublishStrategy();
    publishStrategy.execute(publisher::executionHandler);
}

以下是Junit代码:

@Test
public void testExecute() throws Exception {
    PublishStrategy<Event> publishStrategy = Mockito.mock(PublishStrategy.class);
    Publisher<Event> publisher = Mockito.mock(Publisher.class);
    Mockito.when(publisher.getPublishStrategy()).thenReturn(publishStrategy);
    Mockito.doNothing().when(publishStrategy).execute(publisher::executionHandler);
    PublishJob job = new PublishJob(publisher);
    job.execute(publisher);
    Mockito.verify(publishStrategy, Mockito.times(1)).execute(publisher::executionHandler);
}

在verify方法调用中,我遇到以下mockito异常:

Argument(s) are different! Wanted:
publishStrategy.execute(
    com.test.producer.jobs.PublishJobTest$$Lambda$3/1146825051@6f45df59
);
-> at com.test.producer.jobs.PublishJobTest.testExecute(PublishJobTest.java:23)
Actual invocation has different arguments:
publishStrategy.execute(
    com.producer.jobs.PublishJob$$Lambda$2/1525409936@38e79ae3
);
-> at com.producer.jobs.PublishJob.execute(PublishJob.java:30)


我不明白为什么mockito认为两个lambda是不同的?

更新我没有使用Mockito就解决了。

下面是另一种方法。Omitted empty overridden methods

@Test
public void testExecute() throws Exception {
    PublishStrategy<Event> publishStrategy = new PublishStrategy<Event>() {
        @Override
        public void execute(Consumer<List<Event>> handler) {
            Assert.assertNotNull(handler);
        }
    };
    Publisher<Event> publisher = new AbstractPublisher<Event>() {
        @Override
        public void init(PublishStrategy<Event> publishStrategy) {
            this.publishStrategy = publishStrategy;
        }

        @Override
        public void executionHandler(List<IngestEvent> items) {

        }

        @Override
        public PublishStrategy<IngestEvent> getPublishStrategy() {
            return this.publishStrategy;
        }
    };
    publisher.init(publishStrategy);
    PublishJob job = new PublishJob();
    job.execute(publisher);
}
omhiaaxx

omhiaaxx1#

在Java中,两个对象不相等是因为它们是同一个类的示例!对象相等是因为调用 a.equals(b) 返回true!
在您的例子中,类 PublishJob 可能没有覆盖equals方法,因此,比较两个lambda示例的结果是false。我真的不明白你怎么能通过添加一个equals方法来解决这个问题。
换句话说:当你执行publisher::executionHandler的时候,你创建了两个不同的lambda示例,不管它们是否调用同一个对象,你有两个lambda示例,它们不相等,Mockito方法检查是否相等。
我认为有一种方法可以检验这个:看看你是否能让lambda被执行。2然后验证预期的调用是否发生在那个对象上。

相关问题