我创建了一个自定义的Elastic Search Client。我需要在各种功能上部署单元测试。我该怎么办?

例如,在JUnit中,我使用这些->

assertEquals(expectedOutput, actualOutput);

这里的问题是实际上没有返回值。查询执行和操作事物。我想对各种功能进行单元测试。

例如,我想看看index()是否正常工作。我真的不想真正索引数据并检查它是否已被索引,因为我现在不进行集成测试。我可以做单元测试吗?

以下是我客户的一种方法。我应该如何在这里部署单元测试?
@Override
        public ActionFuture<IndexResponse> index(IndexRequest request)
            {
                TimerContext indexTimerContext=indexTimer.time();
                super.index(request));
                indexTimerContext.stop();
            }

我该如何真正去做呢?

最佳答案

ElasticSearch有自己的Test Framework和( assertion )
教程描述了单元和集成测试!
如果要使用其他框架,则可以使用模拟 easymock 。在您的情况下,您必须检查index(IndexRequest request)方法调用indexTimer.time()indexTimerContext.stop(),因此您必须模拟indexTimer
验证通话。看Java verify void method calls n times with Mockito

编辑
我从未使用过ElasticSearch,但是您的单元测试将如下所示

@Test
public void testIndex() {

    clientTest = Mockito.spy(new MyClient());
    //this is a field, which we mock
    IndexTimer indexTimerSpy = Mockito.spy(new IndexTimer());
    //TimerContext we mock too
    TimerContext timerContextSpy = Mockito.spy(new TimerContext());
    //IndexTimer.time returns our timer context
    Mockito.doReturn(timerContextSpy).when(indexTimerSpy).time();
    //set indexTimer
    clientTest.setIndexTimer(indexTimerSpy);
    //calls method under test
    clientTest.index(null);
    //verify calls of methods
    Mockito.verify(indexTimerSpy).time();
    Mockito.verify(timerContextSpy).stop();

    // Prevent/stub logic when calling super.index(request)
    //Mockito.doNothing().when((YourSuperclass)clientTest).index();

}

10-07 19:45
查看更多