-1
@Repository
public class ElasticRepository {

    private static final Logger LOG = LoggerFactory.getLogger(ElasticRepository.class);

    @Autowired
    private ElasticSearchConfig elasticSearchConfig;

    @Autowired
    private ObjectMapper mapper;

    @Autowired
    private RestHighLevelClient client;


    public void ingest(UnifiedOrder unifiedClubOrder) throws ElasticsearchException, JsonProcessingException {
        IndexRequest indexRequest = new IndexRequest(elasticSearchConfig.elasticSearchIndex)
                .id(unifiedClubOrder.getOrderNo())
                .source(mapper.writeValueAsString(unifiedClubOrder), XContentType.JSON)
                .version(unifiedClubOrder.getModifyTs().getTime())
                .versionType(VersionType.EXTERNAL_GTE);
        ActionListener<IndexResponse> listener = new ActionListener<IndexResponse>() {
            @Override
            public void onResponse(IndexResponse indexResponse) {
                System.out.println("Posted Successfully in ES Index :: ");
            }

            @Override
            public void onFailure(Exception e) {
                System.out.println("Failed to post in ES Index :: ");
                IndexRequest errorIndexRequest = new IndexRequest(elasticSearchConfig.elasticSearchErrorIndex)
                        .id(unifiedClubOrder.getOrderNo())
                        .source(e.getMessage(), XContentType.JSON)
                        .version(unifiedClubOrder.getModifyTs().getTime())
                        .versionType(VersionType.EXTERNAL_GTE);
                ActionListener<IndexResponse> errorIndexListener = new ActionListener<IndexResponse>() {
                    @Override
                    public void onResponse(IndexResponse indexResponse) {
                        System.out.println("Posted Successfully in ES Error Index :: ");
                    }
                    @Override
                    public void onFailure(Exception e) {
                        System.out.println("Failed to post in ES Error Index :: ");
                    }
                };
                client.indexAsync(errorIndexRequest, RequestOptions.DEFAULT, errorIndexListener);
            }
        };
        client.indexAsync(indexRequest, RequestOptions.DEFAULT, listener);
    }
}

==================================================================================

@RunWith(MockitoJUnitRunner.class)
@PrepareForTest({RestHighLevelClient.class})
public class ElasticRepositoryTest {

    @Mock
    private RestHighLevelClient client;

    @Mock
    private ObjectMapper objectMapper;

    @Mock
    private ElasticSearchConfig elasticSearchConfig;

    @InjectMocks
    private ElasticRepository elasticRepository;

    @Test
    public void ingest_Test() throws Exception {
        UnifiedOrder unifiedClubOrder = new UnifiedOrder();
        unifiedClubOrder.setOrderNo("12345");
        unifiedClubOrder.setStatus("purchase");
        unifiedClubOrder.setModifyTs(new Date());
        when(objectMapper.writeValueAsString(unifiedClubOrder)).thenReturn(new ObjectMapper().writeValueAsString(unifiedClubOrder));
        elasticSearchConfig.elasticSearchIndex = "test";
        IndexRequest indexRequest = new IndexRequest(elasticSearchConfig.elasticSearchIndex)
               .id(unifiedClubOrder.getOrderNo())
                .source(objectMapper.writeValueAsString(unifiedClubOrder), XContentType.JSON)
                .version(unifiedClubOrder.getModifyTs().getTime())                
                .versionType(VersionType.EXTERNAL_GTE);        
                PowerMockito.whenNew(IndexRequest.class).withAnyArguments().thenReturn(indexRequest);
        ArgumentCaptor<IndexRequest> argumentCaptorIndexRequest = ArgumentCaptor.forClass(IndexRequest.class);
        PowerMockito.doNothing().when(client).indexAsync(Mockito.any(), Mockito.any(),
                Mockito.any());
        elasticRepository.ingest(unifiedClubOrder);
        verify(client).indexAsync(argumentCaptorIndexRequest.capture(), Mockito.any(), Mockito.any());
        assertTrue(argumentCaptorIndexRequest.getValue() instanceof IndexRequest);
        assertEquals("12345", ((IndexRequest) argumentCaptorIndexRequest.getValue()));
    }

}

===========================================================================================

===============Detailed Exception are below =====================================

java.lang.NullPointerException
    at org.elasticsearch.client.RestHighLevelClient.performRequestAsync(RestHighLevelClient.java:1525)
    at org.elasticsearch.client.RestHighLevelClient.performRequestAsyncAndParseEntity(RestHighLevelClient.java:1498)
    at org.elasticsearch.client.RestHighLevelClient.indexAsync(RestHighLevelClient.java:832)
    at com.sams.mth.club.ingestion.repository.ElasticRepositoryTest.ingest_OnResponse_Test1(ElasticRepositoryTest.java:80)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
    at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)

==================================================================================================

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Misplaced or misused argument matcher detected here:

-> at com.sams.mth.club.ingestion.repository.ElasticRepositoryTest.ingest_OnResponse_Test1(ElasticRepositoryTest.java:80)
-> at com.sams.mth.club.ingestion.repository.ElasticRepositoryTest.ingest_OnResponse_Test1(ElasticRepositoryTest.java:80)
-> at com.sams.mth.club.ingestion.repository.ElasticRepositoryTest.ingest_OnResponse_Test1(ElasticRepositoryTest.java:81)

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
    when(mock.get(anyInt())).thenReturn(null);
    doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
    verify(mock).someMethod(contains("foo"))

This message may appear after an NullPointerException if the last matcher is returning an object 
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
    when(mock.get(any())); // bad use, will raise NPE
    when(mock.get(anyInt())); // correct usage use

Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.


    at org.mockito.internal.runners.DefaultInternalRunner$1$1.testFinished(DefaultInternalRunner.java:70)
    at org.junit.runner.notification.SynchronizedRunListener.testFinished(SynchronizedRunListener.java:56)
    at org.junit.runner.notification.RunNotifier$7.notifyListener(RunNotifier.java:190)
    at org.junit.runner.notification.RunNotifier$SafeNotifier.run(RunNotifier.java:72)
    at org.junit.runner.notification.RunNotifier.fireTestFinished(RunNotifier.java:187)
    at org.junit.internal.runners.model.EachTestNotifier.fireTestFinished(EachTestNotifier.java:38)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:331)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
    at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Chinni
  • 1
  • Issues we are facing in ElasticRepositoryTest class: ---->whenever we are using @RunWith(MockitoJUnitRunner.class), we are facing the below exceptions as, Exception 1 : NullPointerException --> from ElasticRepositoryTest class the above exception hitting at line PowerMockito.doNothing().when(client).indexAsync(Mockito.any(), Mockito.any(), Mockito.any()); – Chinni Oct 18 '21 at 07:31
  • Exception 2 : You cannot use argument matchers outside of verification or stubbing. --> whenever we are using @RunWith(PowerMockRunner.class) even though all lines of code got executed successfully but the execution is not getting stopped. and we are forcefully stopping the execution. please provide your valuable suggestions on this, help is much appreciated. – Chinni Oct 18 '21 at 07:32
  • Edit your question to add how this problem could be reproduce and more details about the workaround. –  Oct 18 '21 at 08:17
  • The test got executed successfullly, after adding @PowerMockIgnore({"javax.net.ssl.*"}). Thanks for your time. – Chinni Oct 19 '21 at 09:36

1 Answers1

0

Adding @PowerMockIgnore({"javax.net.ssl.*"}) annotation to your Test method will ignore above exception.