Java Hbase API throws RetriesExhaustedException when writing JUnit Tests - java

im trying to write JUnit for the following method, which works perfectly when Im executing the method normally, but while invoking the Unit tests, it throws RetriesExhaustedException in result.get().
Method to be Tested:
#Override
public Event findEvents(String id) throws IOException {
Table eventsTable = null;
Connection connection = null;
Event event = null;
boolean iFlag = false;
boolean aFlag = false;
boolean fFlag = false;
try {
connection = connectionPool.get();
eventsTable = connection.getTable(TableName.valueOf(configuration.getEventsTable()));
Get g = new Get(Bytes.toBytes(id.replaceAll(STRPATTERN, "")));
Result r = eventsTable.get(g);// Exception occurs throwing RetiresExhaustedException
if (!r.isEmpty()) {
event = genericRowRowMapperMapper.mapEventDetails(r, HbaseConstants.getEventheaderCf1(),
HbaseConstants.getEventbodyCf1(), iFlag, aFlag, fFlag);
Util.replaceAid(event, id);
}
} finally {
CGUtil.closeTable(eventsTable);
releaseConnection(connection);
}
return event;
}
Test Method:
#Test(expected = Exception.class)
public void findEventsTest() throws Exception {
String flexid = "25652365";
Map<String, Event> eventMapF = new HashMap<>();
Event eventF = new Event();
Activity activityF = new Activity();
activityF.setId("25652365");
eventF.setActivity(activityF);
eventMapF.put("25652365", eventF);
Event evF = hBaseRepository.findEvents(flexid);
assertNull(evF);
}
Stack Trace:
org.apache.hadoop.hbase.client.RetriesExhaustedException: Failed after attempts=3, exceptions:
Wed Jan 08 12:35:36 IST 2020, RpcRetryingCaller{globalStartTime=1578467135791, pause=1000, retries=3}, java.lang.AssertionError
Wed Jan 08 12:35:37 IST 2020, RpcRetryingCaller{globalStartTime=1578467135791, pause=1000, retries=3}, java.lang.AssertionError
Wed Jan 08 12:35:40 IST 2020, RpcRetryingCaller{globalStartTime=1578467135791, pause=1000, retries=3}, java.lang.AssertionError
at org.apache.hadoop.hbase.client.RpcRetryingCaller.callWithRetries(RpcRetryingCaller.java:164)
at org.apache.hadoop.hbase.client.HTable.get(HTable.java:867)
at org.apache.hadoop.hbase.client.HTable.get(HTable.java:832)
at com.citi.gcb.cg.repository.HbaseNativeRepository.findEvents(HbaseNativeRepository.java:103)
at com.citi.gcg.cg.repository.HbaseNativeRepositoryTests.findEventsTest(HbaseNativeRepositoryTests.java:143)
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.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:19)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
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.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Caused by: java.lang.AssertionError
at org.apache.hadoop.hbase.client.ClientScanner.loadCache(ClientScanner.java:484)
at org.apache.hadoop.hbase.client.ClientScanner.next(ClientScanner.java:312)
at org.apache.hadoop.hbase.client.ConnectionManager$HConnectionImplementation.locateRegionInMeta(ConnectionManager.java:1327)
at org.apache.hadoop.hbase.client.ConnectionManager$HConnectionImplementation.locateRegion(ConnectionManager.java:1224)
at org.apache.hadoop.hbase.client.ConnectionManager$HConnectionImplementation.locateRegion(ConnectionManager.java:1208)
at org.apache.hadoop.hbase.client.ConnectionManager$HConnectionImplementation.locateRegion(ConnectionManager.java:1165)
at org.apache.hadoop.hbase.client.ConnectionManager$HConnectionImplementation.getRegionLocation(ConnectionManager.java:997)
at org.apache.hadoop.hbase.client.HRegionLocator.getRegionLocation(HRegionLocator.java:71)
at org.apache.hadoop.hbase.client.RegionServerCallable.prepare(RegionServerCallable.java:87)
at org.apache.hadoop.hbase.client.RpcRetryingCaller.callWithRetries(RpcRetryingCaller.java:140)
I tried changing the increasing rpc timeout property from hbase-site.xml file but still the test case is not passing, its throwing the same exception.

Related

How resolved AsciiDoc Error java.lang.Integer cannot be cast to java.util.List

That code take me an error, i try with Spring Boot and Mockito, Junit4:
#PostMapping(value = Constants.LOGOUT_URL)
public String logout (HttpServletRequest request) throws ApiException {
String authHeader = request.getHeader("Authorization");
if (authHeader != null) {
try {
String tokenValue = authHeader.replace("Bearer", "").trim();
OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
tokenStore.removeAccessToken(accessToken);
} catch (Exception e) {
return HttpStatus.NOT_FOUND.toString();
}
}
return Utils.convertDateTime();
}
#Test
public void logout() throws Exception, ApiException {
//String result = "{\"date\":\"20190212:0000\"}";
//Mockito.when(controller.logout(any())).thenReturn(result);
mockMvc.perform(MockMvcRequestBuilders.post(REST_REQUEST_PATH)
.header("principal", "admin")
.header("authorization", "authtoken")
.contentType(MediaType.APPLICATION_JSON)
.accept("application/json"))
.andExpect(status().isOk())
.andDo(document("logout",
responseFields(fieldWithPath("date").description("Fecha de entrega de la respuesta.")
)));
}
This is the Stack Trace error
14:17:29.972 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Null ModelAndView returned to DispatcherServlet with name '': assuming HandlerAdapter completed request handling
14:17:29.973 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Successfully completed request
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.List
at org.springframework.restdocs.payload.JsonContentHandler.isEmpty(JsonContentHandler.java:147)
at org.springframework.restdocs.payload.JsonContentHandler.getUndocumentedContent(JsonContentHandler.java:119)
at org.springframework.restdocs.payload.AbstractFieldsSnippet.validateFieldDocumentation(AbstractFieldsSnippet.java:242)
at org.springframework.restdocs.payload.AbstractFieldsSnippet.createModel(AbstractFieldsSnippet.java:169)
at org.springframework.restdocs.snippet.TemplatedSnippet.document(TemplatedSnippet.java:83)
at org.springframework.restdocs.generate.RestDocumentationGenerator.handle(RestDocumentationGenerator.java:206)
at org.springframework.restdocs.mockmvc.RestDocumentationResultHandler.handle(RestDocumentationResultHandler.java:55)
at org.springframework.test.web.servlet.MockMvc$1.andDo(MockMvc.java:183)
at com.sodexo.oneapp.api.auth.AuthControllerTest.logout(AuthControllerTest.java:90)
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.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.restdocs.JUnitRestDocumentation$1.evaluate(JUnitRestDocumentation.java:63)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
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.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

exception optaining signature: Could not verify signature

I have the following code, which is taken from ShowSignature example from PDFBox 2. I'm running five tests in which it is called, 4 of them pass without problem (no signature, single signed, double signed, expired signature), but the fifth one is wit Eliptic Curve and it fails.
The fun part is that it passes when I start the JunitTest only on the test-class, but fails as soon as I'm starting it on package or project level.
I would assume something befor the test class is interfering, but can't find a hint what it could be. I checked bouncycastle (1.54 is always used), the java jdk is at any point correctly used (jdk1.8.0_181).
I'm checking the for an exception to be thrown (ERROR_VERIFYING_PDF_SIGNATURE), it is thrown in the classtest, but a different one when starting on higher level.
Error occurs in if (signerInformation.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certFromSignedData)) and has this stack trace:
java.lang.AssertionError:
Expected: (an instance of de.bdr.rt.core.common.api.BusinessLogicException and exception with message a string containing "Die Signatur des PDF-Dokuments konnte nicht verifiziert werden.")
but: an instance of de.bdr.rt.core.common.api.BusinessLogicException <org.bouncycastle.operator.RuntimeOperatorException: exception obtaining signature: Could not verify signature> is a org.bouncycastle.operator.RuntimeOperatorException
Stacktrace was: org.bouncycastle.operator.RuntimeOperatorException: exception obtaining signature: Could not verify signature
at org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder$SigVerifier.verify(Unknown Source)
at org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder$RawSigVerifier.verify(Unknown Source)
at org.bouncycastle.cms.SignerInformation.doVerify(Unknown Source)
at org.bouncycastle.cms.SignerInformation.verify(Unknown Source)
at de.bdr.gematik.tsp.sc.antragsverwaltung.impl.itsp.ds.PDFDigitalSignatureCheckTest.verifyPKCS7(PDFDigitalSignatureCheckTest.java:280)
at de.bdr.gematik.tsp.sc.antragsverwaltung.impl.itsp.ds.PDFDigitalSignatureCheckTest.testPdfSignature(PDFDigitalSignatureCheckTest.java:170)
at de.bdr.gematik.tsp.sc.antragsverwaltung.impl.itsp.ds.PDFDigitalSignatureCheckTest.testPDFECKeySignaturFails(PDFDigitalSignatureCheckTest.java:112)
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.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:239)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
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.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Caused by: java.security.SignatureException: Could not verify signature
at sun.security.ec.ECDSASignature.engineVerify(ECDSASignature.java:325)
at java.security.Signature$Delegate.engineVerify(Signature.java:1222)
at java.security.Signature.verify(Signature.java:655)
at org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder$SignatureOutputStream.verify(Unknown Source)
... 32 more
Caused by: java.security.InvalidAlgorithmParameterException
at sun.security.ec.ECDSASignature.verifySignedDigest(Native Method)
at sun.security.ec.ECDSASignature.engineVerify(ECDSASignature.java:321)
... 35 more
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
at org.junit.Assert.assertThat(Assert.java:956)
at org.junit.Assert.assertThat(Assert.java:923)
at org.junit.rules.ExpectedException.handleException(ExpectedException.java:252)
at org.junit.rules.ExpectedException.access$000(ExpectedException.java:106)
at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:241)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
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.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Code:
private void verifyPKCS7(byte[] byteArray, COSString contents, PDSignature sig)
throws CMSException, CertificateException, StoreException, OperatorCreationException,
NoSuchAlgorithmException, NoSuchProviderException {
CMSProcessable signedContent = new CMSProcessableByteArray(byteArray);
CMSSignedData signedData = new CMSSignedData(signedContent, contents.getBytes());
#SuppressWarnings("unchecked")
Store<X509CertificateHolder> certificatesStore = signedData.getCertificates();
Collection<SignerInformation> signers = signedData.getSignerInfos().getSigners();
SignerInformation signerInformation = signers.iterator().next();
#SuppressWarnings("unchecked")
Collection<X509CertificateHolder> matches = certificatesStore
.getMatches((Selector<X509CertificateHolder>) signerInformation.getSID());
X509CertificateHolder certificateHolder = matches.iterator().next();
X509Certificate certFromSignedData = new JcaX509CertificateConverter().getCertificate(certificateHolder);
System.out.println("certFromSignedData: " + certFromSignedData);
try {
certFromSignedData.checkValidity(sig.getSignDate().getTime());
System.out.println("Certificate valid at signing time");
} catch (CertificateExpiredException ex) {
System.err.println("Certificate expired at signing time");
} catch (CertificateNotYetValidException ex) {
System.err.println("Certificate not yet valid at signing time");
}
if (isSelfSigned(certFromSignedData)) {
System.err.println("Certificate is self-signed, LOL!");
} else {
System.out.println("Certificate is not self-signed");
// todo rest of chain
}
if (signerInformation.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certFromSignedData))) {
System.out.println("Signature verified");
} else {
System.out.println("Signature verification failed");
throw new BusinessLogicException(Messages.ERROR_VERIFYING_PDF_SIGNATURE);
}
}
This is a shortcoming of the PDFBox example. Please change
signerInformation.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certFromSignedData));
to
signerInformation.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build(certFromSignedData));
you may have to register BC as provider:
Security.addProvider(new BouncyCastleProvider());

Curl to rest template using "clientId:clientSecret#servername/oauth/token"

I have a question about how Can I send this curl with rest template?
Thanks in advance
curl -XPOST "server-client-id:server-client-password#localhost:8080/oauth/token" -d "grant_type=client_credentials&client_id=server-client-id&client_secret=server-client-password"
Edited:I had done it. But it didnt work
private static final Logger LOG = LoggerFactory.getLogger(UserServiceRestApi.class);
#Autowired
#Qualifier("userRestTemplateAuthServer")
private RestTemplate restTemplate;
#Value("${userServer.client.id:server-client-id}")
private String clientId;
#Value("${userServer.client.secret:server-client-password}")
private String clientSecret;
#Value("${userServer.url:info-server:info-rest-password#localhost:8080/oauth/token}")
private String url;
/**
* Get auth token from User server
*
* #return
*/
#Retryable(maxAttempts = 3, backoff = #Backoff(delay = 1500))
#Cacheable(value = "userServerToken")
public String generateAuthToken() throws Exception {
LOG.info("Obteniendo Token del servidor de users");
try {
GenerateAuthTokenRequestDTO requestDTO = new GenerateAuthTokenRequestDTO(clientId, clientSecret);
GenerateAuthTokenResponseDTO responseDTO = this.restTemplate.postForObject(url, requestDTO, GenerateAuthTokenResponseDTO.class);
return responseDTO.getAccessToken();
} catch (Throwable ex) {
LOG.error(ex.getStackTrace().toString());
throw new UserServerConnectionException();
}
}
/**
* Flush the cache for userServerToken
*/
#Scheduled(fixedDelay = 30 * 60 * 1000, initialDelay = 500)
#CacheEvict(allEntries = true, value = "userServerToken")
public void flushUserServerTokenConfig() {
}
And this is the stacktrace when I do the test.
java.lang.IllegalArgumentException: Expected scheme-specific part at index 12: info-server:
at java.net.URI.create(URI.java:852)
at org.springframework.web.util.DefaultUriBuilderFactory$DefaultUriBuilder.build(DefaultUriBuilderFactory.java:357)
at org.springframework.web.util.DefaultUriBuilderFactory.expand(DefaultUriBuilderFactory.java:191)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:683)
at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:435)
at com.nsu.duhire.webapi.info.rest.UserServiceRestApi.generateAuthToken(UserServiceRestApi.java:45)
at com.nsu.duhire.webapi.info.InfoApplicationTests.testConnectionWithAuthServer(InfoApplicationTests.java:27)
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.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
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.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)Caused by: java.net.URISyntaxException: Expected scheme-specific part at index 12: info-server:
at java.net.URI$Parser.fail(URI.java:2848)
at java.net.URI$Parser.failExpecting(URI.java:2854)
at java.net.URI$Parser.parse(URI.java:3057)
at java.net.URI.<init>(URI.java:588)
at java.net.URI.create(URI.java:850)
... 36 more
The github repo to the auth server is: https://github.com/NSU-IO/AuthenticationServer

Failed to invoke PACT method

I have this snippet of code, while trying to create a pact file for my service, but it keeps throwing Failed to invoke pact Method. However, when I run the normal client request, it returns a json object, but when trying to run the pact test, it fails. Below is the snippet of the Test class
public class WhatPrimesTest {
#Rule
public PactProviderRuleMk2 provider = new PactProviderRuleMk2("PrimeService", "localhost", 81, this);
#Pact(provider = "PrimeService", consumer = "PrimeServiceClient")
public RequestResponsePact createPact(PactDslWithProvider builder) {
Map<String, String> headers = new HashMap();
headers.put("Content-Type", "application/json");
DslPart etaResults = new PactDslJsonBody()
.stringType("requestedGtin", "4211")
.integerType("nodeId", 6132)
.eachLike("gtinList")
.eachArrayLike("AVAILABLE", 4322)
.asBody();
return builder
.given("There is a prime gtin 4211 from node 6132")
.uponReceiving("A request for gtinList")
.path("/primeService/6132?upc=4211")
.method("GET")
.willRespondWith()
.status(200)
.headers(headers)
.body(etaResults).toPact();
}
#Test
#PactVerification("PrimeService")
public void doTest() {
System.setProperty("pact.rootDir", "../pacts"); // Change output dir for generated pact-files
String gtinExpected = "00000000012348";
String gtinList = new WhatPrime(provider.getPort()).checkEta(6132, "4211");
System.out.println("According to test eta=" + gtinList);
//assertTrue(gtinList.);
//assertArrayEquals("00000000012348", gtinExpected);
}
}
And I get this error when I try to run this test code.
java.lang.RuntimeException: Failed to invoke pact method
at au.com.dius.pact.consumer.BaseProviderRule.getPacts(BaseProviderRule.java:188)
at au.com.dius.pact.consumer.BaseProviderRule$1.evaluate(BaseProviderRule.java:63)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
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.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.reflect.InvocationTargetException
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 au.com.dius.pact.consumer.BaseProviderRule.getPacts(BaseProviderRule.java:186)
... 16 more
Caused by: java.lang.NoSuchMethodError: au.com.dius.pact.model.matchingrules.Category.addRule(Ljava/lang/String;Lau/com/dius/pact/model/matchingrules/MatchingRule;)V
at au.com.dius.pact.consumer.dsl.PactDslJsonBody.stringType(PactDslJsonBody.java:155)
at se.ff.bsc.WhatPrimesTest.createPact(WhatPrimesTest.java:33)
... 21 more
When my service is called, this is what I get as the return.
[ { requestedGtin: "12348", nodeId: 124, gtinList: [ "00000000012348"
], primeOnHandQuantity: { AVAILABLE: 0, CLAIMS: 0 } } ]
Do you think there is something I'm doing wrong, I need help and would appreciate whatever you can comment on. Thanks
When I remove this block of code
DslPart etaResults = new PactDslJsonBody()
.stringType("requestedGtin", "4211")
.integerType("nodeId", 6132)
.eachLike("gtinList")
.eachArrayLike("AVAILABLE", 4322)
.asBody();
and directly parse the expected body in the .body() function, I get this error message
java.net.BindException: Can't assign requested address
at sun.nio.ch.Net.bind0(Native Method)
at sun.nio.ch.Net.bind(Net.java:433)
at sun.nio.ch.Net.bind(Net.java:425)
at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
at sun.net.httpserver.ServerImpl.<init>(ServerImpl.java:100)
at sun.net.httpserver.HttpServerImpl.<init>(HttpServerImpl.java:50)
at sun.net.httpserver.DefaultHttpServerProvider.createHttpServer(DefaultHttpServerProvider.java:35)
at com.sun.net.httpserver.HttpServer.create(HttpServer.java:130)
at au.com.dius.pact.consumer.MockHttpServer.<init>(MockHttpServer.kt:206)
at au.com.dius.pact.consumer.MockHttpServerKt.mockServer(MockHttpServer.kt:34)
at au.com.dius.pact.consumer.ConsumerPactRunnerKt.runConsumerTest(ConsumerPactRunner.kt:12)
at au.com.dius.pact.consumer.BaseProviderRule.runPactTest(BaseProviderRule.java:148)
at au.com.dius.pact.consumer.BaseProviderRule.access$100(BaseProviderRule.java:21)
at au.com.dius.pact.consumer.BaseProviderRule$1.evaluate(BaseProviderRule.java:76)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
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.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Mockito not working on update/create in RESTcontroller

I'm trying to write some tests using Mockito and I managed to write them for findAll and delete operations but for the create and update, they won't work.
#RunWith(MockitoJUnitRunner.class)
public class RentedControllerTest {
#Mock
private RentedService rentalService;
#Mock
private MovieService movieService;
#Mock
private ClientService clientService;
#InjectMocks
private RentedController rentalController;
#InjectMocks
private MovieController movieController;
#InjectMocks
private ClientController clientController;
#Before
public void setUp() throws Exception {
initMocks(this);
}
#Test
public void getMovies() throws Exception {
List<Movie> movies = new ArrayList<>();
movies.add(mock(Movie.class));
// System.out.println(movies.toString());
when(movieService.findAll()).thenReturn(movies);
//// System.out.println(movieService.findAll().toString());
MoviesDto response = movieController.getMovies();
assertEquals("should be 1 movie", 1, response.getMovies().size());
}
#Test
public void updateMovie() throws Exception {
Movie movie = new Movie(2,"Lotr",0, "dir2", 2003);
MovieDto movieDto = mock(MovieDto.class);
System.out.println(movie.toString());
when(movieService.updateMovie(anyInt(), anyString(), anyInt(), anyString(), anyInt())).thenReturn(movie);
// Movie m = new Movie();
// m = movieService.updateMovie(2,"Lotrrrrr",0, "dir2", 2003);
// System.out.println(m.toString());
Map<String, MovieDto> map = movieController.updateMovie(2, movieDto);
System.out.println(map.toString());
assertEquals("Title should be Lots", "Lotr", map.get("movie").getName());
}
#Test
public void createMovie() throws Exception {
Movie movie = new Movie(2,"Lotr",0, "dir2", 2003);
MovieDto movieDto = mock(MovieDto.class);
when(movieService.createMovie(anyInt(), anyString(), anyInt(), anyString(), anyInt())).thenReturn(movie);
Map<String, MovieDto> map = movieController.createMovie(movieDto);
assertEquals("Title should be Lotr", "Lotr", map.get("movie").getName());
}
#Test
public void deleteMovie() throws Exception {
ResponseEntity response = movieController.deleteMovie(1);
assertEquals("Http status should be OK", HttpStatus.OK, response.getStatusCode());
}
}
So the line "when(movieService.update....) work's just fine. I tested it with the write lines as you can see in the code and it works. The problem is here
Map<String, MovieDto> map = movieController.updateMovie(2, movieDto);
I gives me NullPointerException inside that method. The method looks like this:
#RequestMapping(value = "/movies/{movieId}", method = RequestMethod.PUT, consumes = CatalogMediaType.API_JSON)
public Map<String, MovieDto> updateMovie(#PathVariable final Integer movieId,
#RequestBody final MovieDto movieDto) {
log.trace("updateMovie: movieId={} movieDto={}", movieId, movieDto);
Movie movie = movieService.updateMovie(movieId, movieDto.getMovie().getName(), movieDto.getMovie().getNumberofrentals(), movieDto.getMovie().getDirector(), movieDto.getMovie().getYear());
Map<String, MovieDto> movieDtoMap = new HashMap<>();
movieDtoMap.put("movie", new MovieDto(movie));
log.trace("updateMovie: movieDtoMap={}", movieDtoMap);
return movieDtoMap;
}
The application itself works perfectly, the problem arises only when runing the mockito tests.
java.lang.NullPointerException
at ro.ubb.stcatalog.web.controller.MovieController.updateMovie(MovieController.java:41)
at ro.ubb.stcatalog.web.controller.RentedControllerTest.updateMovie(RentedControllerTest.java:82)
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:483)
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.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
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.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
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:119)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
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:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
2016-05-26T23:51:52,845 TRACE [main]: MovieController - createMovie: moviesDto=Mock for MovieDto, hashCode: 825249556
java.lang.NullPointerException
at ro.ubb.stcatalog.web.controller.MovieController.createMovie(MovieController.java:54)
at ro.ubb.stcatalog.web.controller.RentedControllerTest.createMovie(RentedControllerTest.java:92)
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:483)
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.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
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.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
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:119)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
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:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
I don't really understand what the problem is if the findAll and delete work just fine... Any ideas?
I believe the mocking of MovieDto class is causing the NPE, as your controller is expecting a few params to be present in the DTO, which are not being set by the mock(), such as movieDto.getMovie().getName().
Create a MovieDto object from scratch with all the required params, or set the params post mocking, and you should be fine.
The following should work.
#Test
public void updateMovie() throws Exception {
Movie movie = new Movie(2,"Lotr",0, "dir2", 2003);
MovieDto movieDto = mock(MovieDto.class);
// Added the following line
movieDto.setMovie(movie);
System.out.println(movie.toString());
when(movieService.updateMovie(anyInt(), anyString(), anyInt(), anyString(), anyInt())).thenReturn(movie);
Map<String, MovieDto> map = movieController.updateMovie(2, movieDto);
System.out.println(map.toString());
assertEquals("Title should be Lots", "Lotr", map.get("movie").getName());
}
Looks like some dependency for the MovieController isn't getting set.
java.lang.NullPointerException
at ro.ubb.stcatalog.web.controller.MovieController.createMovie(MovieController.java:54)
You need to populate movieDto first. When you are doing get in the actual code its like you are doing get on a null which gives a NullPointer. And also Both values should be same. In when condition you are telling movieId as anyInt() and in the actual method call you are giving it as 2. That won't work. Both should be same as below.
when(movieService.updateMovie(**2**, anyString(), anyInt(), anyString(), anyInt())).thenReturn(movie);
Map<String, MovieDto> map = movieController.updateMovie(**2**, movieDto);

Categories