Spring Data JPA findById() throwing ClassCastException - java

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!

Related

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.

Java with mockito fails

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.

Unable to find a MessageBodyReader of content-type application/json and type int

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

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