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());
Related
I am trying to do unit test for JSONException. Below it's the code:
public void testException(JSONObject jsonObj){
try{
String test = jsonObj.getString("test");
}catch(JSONException e){
}
}
But in the Unit tests when I give the below it throws a different exception:
#Test (expected=JSONException.class){
mymockClass.testException(jsonObj);
}
java.lang.AssertionError: Expected exception: org.codehaus.jettison.json.JSONException
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:32)
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.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.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)
Its because test expects that exception will be actually thrown out of test method, but you are catching it - thats why you have "expected exception has not been thrown" exception. Remove try-catch block and add throws to method signature.
public void testException(JSONObject jsonObj) throws JSONException{
String test = jsonObj.getString("test");
}
I have a method that is using findById() method of Spring Data JPA. However, this method is returning ClassCastException on line number 1 of the getSupportedKey() method where I am calling findById():
MySupportedKey cannot be cast to java.util.Optional
private MySupportedKey getSupportedKey(String tenant, String key) {
Optional<MySupportedKey> mySupportedKeyOptional = mySupportedKeyRepository.findById(new MySupportedKeyId(tenant, key));
MySupportedKey mySupportedKey= null;
if(mySupportedKeyOptional !=null) {
mySupportedKey= mySupportedKeyOptional.orElse(null);
}
return mySupportedKey;
}
I have been beating my head for a long time but I am not getting anything. Please help me in getting this resolved. I am using spring-data-jpa: 2.0.8.RELEASE.
Adding the Repository Source Code:
public interface MySupportedKeyRepository extends JpaRepository<MySupportedKey, MySupportedKeyId> {
List<MySupportedKey> findByIdTenant(#NotNull String tenant);
}
Adding the complete stack trace of error:
java.lang.ClassCastException: com.test.service.user.entity.MySupportedKey cannot be cast to java.util.Optional
at com.test.service.user.repository.MySupportedKeyRepository$MockitoMock$1304362870.findById(Unknown Source)
at com.test.service.user.repository.MySupportedKeyRepository$MockitoMock$1304362870.findById(Unknown Source)
at com.test.service.user.userpreferences.PreferencesServiceImpl.getSupportedKey(PreferencesServiceImpl.java:217)
at com.test.service.user.userpreferences.PreferencesServiceImpl.updateUserPreferences(PreferencesServiceImpl.java:167)
at com.test.service.user.userpreferences.PreferencesServiceImpl.lambda$2(PreferencesServiceImpl.java:92)
at java.util.ArrayList.forEach(Unknown Source)
at com.test.service.user.userpreferences.PreferencesServiceImpl.updateUserPreferences(PreferencesServiceImpl.java:92)
at com.test.service.user.preferences.PreferencesServiceImplTest.updateUserPreferences(PreferencesServiceImplTest.java:300)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
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.mockito.internal.junit.JUnitRule$1.evaluateSafely(JUnitRule.java:52)
at org.mockito.internal.junit.JUnitRule$1.evaluate(JUnitRule.java:43)
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.RunPrepareTestInstanceCallbacks.evaluate(RunPrepareTestInstanceCallbacks.java:64)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.springframework.test.context.junit4.statements.SpringFailOnTimeout.evaluate(SpringFailOnTimeout.java:87)
at org.springframework.test.context.junit4.statements.ProfileValueChecker.evaluate(ProfileValueChecker.java:103)
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.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.springframework.test.context.junit4.statements.ProfileValueChecker.evaluate(ProfileValueChecker.java:103)
at org.springframework.test.context.junit4.rules.SpringClassRule$TestContextManagerCacheEvictor.evaluate(SpringClassRule.java:230)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
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)
You set up a Mockito mock for the repository and probably told it to return a MySupportedKey instance when findById gets called.
But since findById is supposed to return an Optional you now get the exception.
You can see that this is coming from Mockito in the very first two lines of the stack trace.
java.lang.ClassCastException: com.test.service.user.entity.MySupportedKey cannot be cast to java.util.Optional
at com.test.service.user.repository.MySupportedKeyRepository$MockitoMock$1304362870.findById(Unknown Source)
Modify the Optional handling in your below method to get the correct representation like below:
private MySupportedKey getSupportedKey(String tenant, String key) {
Optional<MySupportedKey> mySupportedKeyOptional = mySupportedKeyRepository.findById(new MySupportedKeyId(tenant, key));
MySupportedKey mySupportedKey= null;
if(mySupportedKeyOptional.isPresent()) {
mySupportedKey= mySupportedKeyOptional.get();
}
return mySupportedKey;
}
Cannot add comment, just wanted to elaborate on Jens answer since it took me a while to figure out how to fix this (being a newbie).
To fix the issue I changed my code from:
when(mongoRepository.findById(Mockito.anyString())).thenAnswer(new Answer<MongoObj>() {
#Override
public MongoObj answer(InvocationOnMock invocation) throws Throwable {
MongoObj repush = new MongoObj();
//Some other code
return repush;
}
});
To
when(mongoRepository.findById(Mockito.anyString())).thenAnswer(new Answer<Optional<MongoObj>>() {
#Override
public Optional<MongoObj> answer(InvocationOnMock invocation) throws Throwable {
MongoObj repush = new MongoObj();
//Some other code
return Optional.of(repush);
}
});
Hope this helps!
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)
I have following method in my service to mock AWS sqs
#Override
public Message recieveMessage(String queueUrl) {
Objects.requireNonNull(queueUrl);
ReceiveMessageRequest request = new ReceiveMessageRequest().withQueueUrl(queueUrl).withMaxNumberOfMessages(1);
ReceiveMessageResult receiveMessageResult = this.sqsClient.receiveMessage(request);
// As per the spec, we need to return only one message.
return receiveMessageResult.getMessages().get(0);
}
#Override
public int getMessageCount(String queueUrl) {
GetQueueAttributesResult queueAttributes = sqsClient.getQueueAttributes(queueUrl, Arrays.asList("ApproximateNumberOfMessages"));
return Integer.valueOf(queueAttributes.getAttributes().get("ApproximateNumberOfMessages"));
}
and following are my test cases for these methods using mockito are failing with NPE.
#Test
public void testRecieveMessage() {
Message message = new Message();
message.setBody("Message Body");
List<Message> messages = new ArrayList<>();
messages.add(message);
ReceiveMessageResult result = new ReceiveMessageResult();
result.setMessages(messages);
when(mock(ReceiveMessageResult.class).getMessages()).thenReturn(messages);
when(mock(List.class).get(0)).thenReturn(message);
when(this.amazonSQSClient.receiveMessage(mock(ReceiveMessageRequest.class))).thenReturn(result);
this.amazonQueueService.recieveMessage(anyString());
verify(this.amazonSQSClient, times(1)).receiveMessage(mock(ReceiveMessageRequest.class));
//Assert.assertNotNull(msg);
}
java.lang.NullPointerException
at com.example.queue.service.impl.AmazonSQSService.recieveMessage(AmazonSQSService.java:46)
at com.example.AmazonSQSServiceTest.testRecieveMessage(AmazonSQSServiceTest.java:77)
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.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.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:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
#Test
public void testMessageCount() {
GetQueueAttributesResult result = new GetQueueAttributesResult();
result.addAttributesEntry("ApproximateNumberOfMessages", "10");
List<String> attrs = Arrays.asList("ApproximateNumberOfMessages");
when(this.amazonSQSClient.getQueueAttributes(anyString(), eq(attrs))).thenReturn(result);
this.amazonQueueService.getMessageCount(anyString());
}
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
2 matchers expected, 1 recorded:
-> at com.example.AmazonSQSServiceTest.testMessageCount(AmazonSQSServiceTest.java:96)
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));
For more info see javadoc for Matchers class.
at com.example.queue.service.impl.AmazonSQSService.getMessageCount(AmazonSQSService.java:58)
at com.example.AmazonSQSServiceTest.testMessageCount(AmazonSQSServiceTest.java:96)
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.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.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:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Am I missing something?
Here is what your code does:
ReceiveMessageRequest request = new ReceiveMessageRequest().withQueueUrl(queueUrl).withMaxNumberOfMessages(1);
ReceiveMessageResult receiveMessageResult = this.sqsClient.receiveMessage(request);
So it creates a new request, and passes ths new request to sqsClient.receiveMessage().
Here's how you test that:
when(this.amazonSQSClient.receiveMessage(mock(ReceiveMessageRequest.class))).thenReturn(result);
So your test tells th mock client to return result when receiveMessage() is called with a mock ReceiveMessageRequest.
So that can't work. The mock ReceiveMessageRequest is not equal to the new request used in the code. You need to do something like
when(this.amazonSQSClient.receiveMessage(any(ReceiveMessageRequest.class))).thenReturn(result);
So that, whetever the request passed to receiveMessage, the mock client returns the result.
Regarding your second question:
this.amazonQueueService.getMessageCount(anyString());
doesn't make sense. You need to call your method with a real, given string.
I got a main project, that I have to test now...
I made a second project for that, in that project, I pasted the interfaces and entities from the main project, and now I made a simple jUnit test case...
Looks like this:
public class TestLogin {
String path = "http://localhost:8080/rest/dss"; //thats the right path...
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget rtarget = client.target(path);
DssRest rest = rtarget.proxy(DssRest.class);
#Test
public void test() {
assert(rest.login(null, "Test", "Test") != -1);
}
}
DssRest, interface
#POST
#Produces(MediaType.APPLICATION_JSON)
#Path("/login/{userName}/{password}")
int login(#Context HttpServletRequest req, #PathParam("userName") String userName,
#PathParam("password") String password);
from there I go to the DssBean, where the function is that I wanna test
#Override
public int login(HttpServletRequest req, String userName, String password) {
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget rtarget = client.target(".../rest/mw"); //real path
MWRest rest = rtarget.proxy(MWRest.class);
int userId = rest.login(userName, password);
...
return userId; //it always is > -1
}
From there, I call the MWRest, an interface of my second project...and that project has the same function, which returns an INT, 12 for exemple...
now....to test that, made a junit test suite
#RunWith(Suite.class)
#SuiteClasses({TestLogin.class})
public class AllTests {
}
Before I run it, I made sure, the 2 projects I need to test are running...
Then I run the suite, as jUnit test, and on the JUnit console, there is this error, which I simply cannot figure out.
I hope you can help....thx
javax.ws.rs.client.ResponseProcessingException: javax.ws.rs.ProcessingException: Unable to find a MessageBodyReader of content-type application/json and type int
at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.extractResult(ClientInvocation.java:140)
at org.jboss.resteasy.client.jaxrs.internal.proxy.extractors.BodyEntityExtractor.extractEntity(BodyEntityExtractor.java:58)
at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientInvoker.invoke(ClientInvoker.java:104)
at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientProxy.invoke(ClientProxy.java:62)
at com.sun.proxy.$Proxy24.login(Unknown Source)
at test.dss.TestLogin.test(TestLogin.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
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.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.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:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: javax.ws.rs.ProcessingException: Unable to find a MessageBodyReader of content-type application/json and type int
at org.jboss.resteasy.core.interception.ClientReaderInterceptorContext.throwReaderNotFound(ClientReaderInterceptorContext.java:39)
at org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext.getReader(AbstractReaderInterceptorContext.java:73)
at org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext.proceed(AbstractReaderInterceptorContext.java:50)
at org.jboss.resteasy.plugins.interceptors.encoding.GZIPDecodingInterceptor.aroundReadFrom(GZIPDecodingInterceptor.java:59)
at org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext.proceed(AbstractReaderInterceptorContext.java:53)
at org.jboss.resteasy.client.jaxrs.internal.ClientResponse.readFrom(ClientResponse.java:248)
at org.jboss.resteasy.client.jaxrs.internal.ClientResponse.readEntity(ClientResponse.java:181)
at org.jboss.resteasy.specimpl.BuiltResponse.readEntity(BuiltResponse.java:211)
at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.extractResult(ClientInvocation.java:104)
... 36 more