Java with mockito fails - java

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.

Related

ContractCallException when I deploy contracts success and call function contractURI()

When I deploy contracts success and call function contractURI(), it throws an error:
org.web3j.tx.exceptions.ContractCallException: Empty value (0x) returned from contract
at org.web3j.tx.Contract.executeCallSingleValueReturn(Contract.java:314)
at org.web3j.tx.Contract.lambda$executeRemoteCallSingleValueReturn$1(Contract.java:400)
at org.web3j.protocol.core.RemoteCall.send(RemoteCall.java:42)
at NFT721Test.deployNFT721(NFT721Test.java:28)
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.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
and my code:
public class NFT721Test {
#Test
public void deployNFT721() throws Exception {
// Web3j web3j = Web3j.build(new HttpService("http://192.168.2.17:8545/"));
Web3j web3j = Web3j.build(new HttpService("http://192.168.159.101:8545/"));
BigInteger chainId = web3j.ethChainId().send().getChainId();
RawTransactionManager transactionManager = new RawTransactionManager(web3j, getCredentials(),chainId.longValue());
// Greeter greeter = Greeter.deploy(web3j,transactionManager,new DefaultGasProvider(),"Hello EVM").send();
NFT721 nft721 = NFT721.deploy(web3j,transactionManager,new StaticGasProvider(BigInteger.valueOf(22_000_000_000l),BigInteger.valueOf(6_700_000l)),
"NFT721.01","harry","0xb6cbf492ee64e67df6f0348de460896f0974e783","ipfs://","ipfs://").send();
String contractURI = nft721.contractURI().send();
System.out.println("contractURI::"+contractURI);
String tokenURIPrefix = nft721.tokenURIPrefix().send();
System.out.println("tokenURIPrefix:::"+tokenURIPrefix);
}
private Credentials getCredentials () {
return Credentials.create("0x3962281158193372293187638892977826627782389871655162191585611137");
}
}

java.lang.IllegalArgumentException: legacyRetryPolicy cannot be null

I am writing a junit test case to call an api deployed on aws api gateway.
The code is :
#Test
public void testAwsApiUtilsMakeRequest() throws Exception {
RetryPolicy retryPolicy = new RetryPolicy(PredefinedRetryPolicies.DEFAULT_RETRY_CONDITION,
PredefinedRetryPolicies.DEFAULT_BACKOFF_STRATEGY,
3, true);
ClientConfiguration cfg = Mockito.mock(ClientConfiguration.class);
RetryPolicyAdapter rpa = new RetryPolicyAdapter(retryPolicy, cfg);
System.out.println(rpa.getLegacyRetryPolicy());
cfg.setRetryPolicy(rpa.getLegacyRetryPolicy());
cfg.withMaxErrorRetry(3);
Request request = Mockito.mock(Request.class);
request.setHttpMethod(HttpMethodName.GET);
request.setEndpoint(new URI("http://localhost:" + port));
request.setResourcePath("/myapro-1.0.0/profiles/" + "123");
request.addHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON.toString());
Response<AmazonWebServiceResponse<String>> awsResponse = Mockito.mock(Response.class);
Mockito.when(awsApiUtils.postToAwsClient(request, cfg))
.thenReturn(awsResponse);
Mockito.when(awsApiUtils.makeRequest(request))
.thenReturn(awsResponse.getAwsResponse().getResult());
//assertThat(sdReprocessController.getProfileInfo("123"));
}
When I am running the test I am getting the error: java.lang.IllegalArgumentException: legacyRetryPolicy cannot be null
Does anyone know how to resolve the issue / how to set legacyRetryPolicy? Thanks.
Here is the log:
java.lang.IllegalArgumentException: legacyRetryPolicy cannot be null
at com.amazonaws.util.ValidationUtils.assertNotNull(ValidationUtils.java:37)
at com.amazonaws.retry.RetryPolicyAdapter.<init>(RetryPolicyAdapter.java:36)
at com.amazonaws.http.AmazonHttpClient.<init>(AmazonHttpClient.java:347)
at com.amazonaws.http.AmazonHttpClient.<init>(AmazonHttpClient.java:320)
at com.amazonaws.http.AmazonHttpClient.<init>(AmazonHttpClient.java:308)
at com.amazonaws.http.AmazonHttpClient.<init>(AmazonHttpClient.java:286)
at com.amazonaws.http.AmazonHttpClient.<init>(AmazonHttpClient.java:269)
at com.amazonaws.http.AmazonHttpClient.<init>(AmazonHttpClient.java:253)
at org.act.leap.util.AwsApiUtils.postToAwsClient(AwsApiUtils.java:62)
at org.act.leap.resttemplate.controller.SdReprocessControllerTest.testAwsApiUtilsMakeRequest(SdReprocessControllerTest.java:251)
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.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
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:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)

How to write a Mockito test for Java 8 Predicate

I am using Spring Boot REST and Mockito. How can I write a test case?
Error:
java.lang.NullPointerException
at java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1011)
at java.util.concurrent.ConcurrentHashMap$KeySetView.add(ConcurrentHashMap.java:4595)
at com.mastercard.customer.data.management.refdata.service.RegionService.lambda$2(RegionService.java:58)
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:174)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.stream.Streams$StreamBuilderImpl.forEachRemaining(Streams.java:419)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at com.mastercard.customer.data.management.refdata.service.RegionService.findAllRegions(RegionService.java:49)
at com.mastercard.customer.data.management.refdata.service.RegionServiceTest.findAllRegions_SuccessTest(RegionServiceTest.java:68)
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.mockito.internal.runners.DefaultInternalRunner$1$1.evaluate(DefaultInternalRunner.java:44)
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:74)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:80)
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)
Code
public List<Employee> findAllEmployees() {
List<Object> obj = mongoTemplate.query(Department.class).distinct("employees").all();
List<Employee> employees = null;
if (!CollectionUtils.isEmpty(obj)) {
employees = obj.stream().map(e -> (Employee) e).filter(distinctByKey(Employee::getEmployeeCd)).collect(Collectors.toList());
}
return employees;
}
public <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
Test case
#Test
public void findEmp() {
when(mongoTemplate.query(Department.class)).thenReturn(executableDepartment);
when(mongoTemplate.query(Department.class).distinct("employees")).thenReturn(distinctDepartment);
when(mongoTemplate.query(Department.class).distinct("employees").all()).thenReturn(obj);
when(obj.stream()).thenReturn(Stream.of(obj));
when(obj.stream().map(e -> (Region) e).thenReturn(Stream.of(region));
assertNotNull(empService.findAllRegions());
}
1) Try to set up you mocking one by one instead of cascading the calls:
when(mongoTemplate.query(Department.class)).thenReturn(executableDepartment);
when(executableDepartment).distinct("employees")).thenReturn(distinctDepartment);
when(distinctDepartment.all()).thenReturn(obj);
The executableDepartment and distinctDepartment need to be mocks as well of course.
2) Do not mock the List interface. Feed it with pre-configured data and allow the SUT to work on it as it is. Sp mocking should only be used in this part:
mongoTemplate.query(Department.class).distinct("employees").all();
So the part that provides data. But leave the actual logic to run as it is.

Assertj-swagger throws org.assertj.core.error.AssertJMultipleFailuresError Multiple Failures when executing test

I have a spring boot api application and I used springfox to generate swaggerv2 api documentation and I created a test to see if my api definitions are correct.
Heres how my configuration looks like:
#Configuration
#EnableSwagger2
public class SpringFoxConfig {
#Value("${my.app.version}")
private String appVersion;
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).groupName("My App").select()
.apis(RequestHandlerSelectors.basePackage("my.com.app.controller"))
.paths(regex("/api/MyAppName.*")).build()
.globalOperationParameters(
Arrays.asList(new ParameterBuilder().name("UserKey").description("Unique user key.")
.modelRef(new ModelRef("string")).parameterType("header").required(true).build()))
.apiInfo(apiInfo()).securitySchemes(Arrays.asList(apiKey()));
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("My App API Documentaion")
.description("This documentation is for the MyApp.").version(appVersion)
.license("MyApp.cc").licenseUrl("https://myapp.com/").build();
}
private ApiKey apiKey() {
return new ApiKey("apiKey", "APIKEY", "header");
}
}
Here's how my test looks:
#Test
public void shouldFindNoDifferences() {
File implFirstSwaggerLocation = new File(
MyTest.class.getResource("/swagger.json").getFile());
File designFirstSwaggerLocation = new File(
MyTest.class.getResource("/swagger.yaml").getFile());
SwaggerAssertions.assertThat(implFirstSwaggerLocation.getAbsolutePath())
.isEqualTo(designFirstSwaggerLocation.getAbsolutePath());
}
It's exactly what they have from their examples. When I run my test It throws this exception below:
Stack trace:
org.assertj.core.error.AssertJMultipleFailuresError:
Multiple Failures (1 failure)
-- failure 1 --
[Checking Paths]
Expecting:
<["/api/myAppName",
"/api/myAppName/eventTypes",
"/api/myAppName/initialize",
"/api/myAppName/latest/{type}/{user}",
"/api/myAppName/stats/due/{ids}/custom/{days}",
"/api/myAppName/stats/due/{ids}/{period}",
"/api/myAppName/stats/orgs/most/{ids}/{period}",
"/api/myAppName/stats/orgs/{id}/{period}",
"/api/myAppName/stats/{ids}/{period}",
"/api/myAppName/stats/{ids}/{period}/{days}",
"/api/myAppName/summarize",
"/api/myAppName/{id}",
"/api/myAppName/{source}/events",
"/api/myAppName/{source}/events/batch"]>
to contain only:
<["/v2/api/myAppName/stats/orgs/{id}/{period}",
"/v2/api/myAppName/{source}/events/batch",
"/v2/api/myAppName/initialize",
"/v2/api/myAppName/eventTypes",
"/v2/api/myAppName/stats/due/{ids}/{period}",
"/v2/api/myAppName/stats/orgs/most/{ids}/{period}",
"/v2/api/myAppName/{source}/events",
"/v2/api/myAppName/{id}",
"/v2/api/myAppName/latest/{type}/{user}",
"/v2/api/myAppName/stats/due/{ids}/custom/{days}",
"/v2/api/myAppName/stats/{ids}/{period}",
"/v2/api/myAppName",
"/v2/api/myAppName/summarize",
"/v2/api/myAppName/stats/{ids}/{period}/{days}"]>
elements not found:
<["/v2/api/myAppName/stats/orgs/{id}/{period}",
"/v2/api/myAppName/{source}/events/batch",
"/v2/api/myAppName/initialize",
"/v2/api/myAppName/eventTypes",
"/v2/api/myAppName/stats/due/{ids}/{period}",
"/v2/api/myAppName/stats/orgs/most/{ids}/{period}",
"/v2/api/myAppName/{source}/events",
"/v2/api/myAppName/{id}",
"/v2/api/myAppName/latest/{type}/{user}",
"/v2/api/myAppName/stats/due/{ids}/custom/{days}",
"/v2/api/myAppName/stats/{ids}/{period}",
"/v2/api/myAppName",
"/v2/api/myAppName/summarize",
"/v2/api/myAppName/stats/{ids}/{period}/{days}"]>
and elements not expected:
<["/api/myAppName",
"/api/myAppName/eventTypes",
"/api/myAppName/initialize",
"/api/myAppName/latest/{type}/{user}",
"/api/myAppName/stats/due/{ids}/custom/{days}",
"/api/myAppName/stats/due/{ids}/{period}",
"/api/myAppName/stats/orgs/most/{ids}/{period}",
"/api/myAppName/stats/orgs/{id}/{period}",
"/api/myAppName/stats/{ids}/{period}",
"/api/myAppName/stats/{ids}/{period}/{days}",
"/api/myAppName/summarize",
"/api/myAppName/{id}",
"/api/myAppName/{source}/events",
"/api/myAppName/{source}/events/batch"]>
at DocumentationDrivenValidator.validatePaths(DocumentationDrivenValidator.java:108)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at io.github.robwin.swagger.test.DocumentationDrivenValidator.validateSwagger(DocumentationDrivenValidator.java:88)
at io.github.robwin.swagger.test.SwaggerAssert.isEqualTo(SwaggerAssert.java:75)
at io.github.robwin.swagger.test.SwaggerAssert.isEqualTo(SwaggerAssert.java:87)
at my.com.app.definitions.MyTest.shouldFindNoDifferences(MyTest.java:58)
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:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
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:542)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
I think I'm missing something.
It was my carelessness that resulted to this problem but thanks to Roddy's comment I was able to notice my mistake.
In my assertj-swagger.properties file there contains assertj.swagger.pathsPrependExpected=/v2 property that causes this issue.

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)

Categories