#java #azure #unit-testing #mockito #powermockito
Вопрос:
@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)
Комментарии:
1. Проблемы, с которыми мы сталкиваемся в классе ElasticRepositoryTest: —->всякий раз, когда мы используем @RunWith(MockitoJUnitRunner.class), мы сталкиваемся с приведенными ниже исключениями, как Исключение 1 : Исключение NullPointerException —>> из класса ElasticRepositoryTest, указанное выше исключение попадает в строку PowerMockito. Пожертвование().когда(клиент).indexAsync(Mockito.any(), Mockito.any(), Mockito.any());
2. Исключение 2 : Вы не можете использовать сопоставители аргументов вне проверки или заглушки. —> всякий раз, когда мы используем @RunWith(PowerMockRunner.class) несмотря на то, что все строки кода были успешно выполнены, но выполнение не останавливается. и мы решительно останавливаем казнь. пожалуйста, предоставьте свои ценные предложения по этому вопросу, мы будем очень признательны за помощь.
3. Отредактируйте свой вопрос, чтобы добавить, как можно решить эту проблему, и более подробную информацию об обходном пути.
4. Тест был успешно выполнен после добавления @PowerMockIgnore({«javax.net.ssl.*»}). Спасибо, что уделили мне время.
5. Отлично! Я ответил, вы должны отметить, примите ответ как решение.
Ответ №1:
Добавление @PowerMockIgnore({"javax.net.ssl.*"})
аннотации к вашему методу тестирования будет игнорировать указанное выше исключение.