Cannot handle expected exception in integration test - java

I cannot pass test notFoundFoo since I get NestedServletException excpetion instead of expected FooNotFoundException exception.
What I do wrong in my test?
Controller:
#RestController
#RequestMapping("/api/foo")
public class FooController {
#Autowired
private FooService fooService;
#GetMapping("/{fooId}/status")
#ResponseStatus(HttpStatus.OK)
public PaymentStatus retrievePaymentStatus(#PathVariable String fooId) {
PaymentStatus paymentStatus = fooService.retrievePaymentStatus(fooId);
if (paymentStatus == null) {
throw new InvoiceNotFoundException();
}
// Preconditions.checkNotNull(paymentStatus, new FooNotFoundException());
return paymentStatus;
}
}
FooNotFoundException:
#ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Foo not found")
public class FooNotFoundException extends RuntimeException {
public FooNotFoundException() {
}
public FooNotFoundException(String message) {
super(message);
}
}
Tests:
#RunWith(SpringRunner.class)
#SpringBootTest(classes = App.class)
#AutoConfigureMockMvc
public class FooControllerTest {
#Autowired
FooRepository fooRepository;
#Autowired
BloomFilterManager bloomFilterManager;
#Autowired
private MockMvc mockMvc;
private MediaType CONTENT_TYPE = new MediaType(MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(),
Charset.forName("utf8"));
#Test
public void foundFooWithPaymentStatus() throws Exception {
Faker faker = new Faker();
Foo.PaymentStatus[] paymentStatuses = Foo.PaymentStatus.values();
Foo foo= fooRepository.save(new Foo(
faker.number().randomNumber(),
faker.lorem().word(),
faker.number().randomDigit(),
new BigDecimal(Math.random()),
paymentStatuses[faker.number().numberBetween(0, paymentStatuses.length)],
faker.date().between(new Date(), DateUtils.addDays(new Date(), 13))
));
bloomFilterManager.getBloomFilter().put(foo.getId());
RequestBuilder requestBuilder = MockMvcRequestBuilders
.get("/api/foo/{fooId}/status", foo.getId())
.accept(CONTENT_TYPE);
MvcResult result = mockMvc.perform(requestBuilder)
.andExpect(status().isOk())
.andExpect(content().contentType(CONTENT_TYPE))
.andReturn();
String expected = "\"" + foo.getPaymentStatus() + "\"";
assertEquals(expected, result.getResponse().getContentAsString());
}
#Test(expected = FooNotFoundException.class)
public void notFoundFoo() throws Exception {
String fooId = "100000000000000";
RequestBuilder requestBuilder = MockMvcRequestBuilders
.get("/api/foo/{fooId}/status", fooId)
.accept(CONTENT_TYPE);
mockMvc.perform(requestBuilder)
.andExpect(status().isNotFound())
.andExpect(content().contentType(CONTENT_TYPE));
}
Output:
java.lang.Exception: Unexpected exception, expected<org.learn.foo.exception.FooNotFoundException> but was<org.springframework.web.util.NestedServletException>
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:28)
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:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
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:191)
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: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: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException: org.learn.foo.exception.FooNotFoundException
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
at org.learn.integration.FooControllerTest.notFoundFoo(FooControllerTest.java:100)
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.ExpectException.evaluate(ExpectException.java:19)
... 28 more
Caused by: java.lang.NullPointerException: org.learn.foo.exception.FooNotFoundException
at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:900)
at org.learn.foo.controller.FooController.retrievePaymentStatus(FooController.java:22)
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.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
... 58 more
UPDATED:
MockHttpServletRequest:
HTTP Method = GET
Request URI = /api/foo/100000000000000/status
Parameters = {}
Headers = {Accept=[application/json;charset=UTF-8]}
Handler:
Type = org.wixanz.omniva.foo.controller.FooController
Method = public org.wixanz.omniva.foo.domain.foo$PaymentStatus org.wixanz.omniva.foo.controller.FooController.retrievePaymentStatus(java.lang.String)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = org.wixanz.omniva.foo.exception.InvoiceNotFoundException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 404
Error message = Foo not found
Headers = {}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.Exception: Unexpected exception, expected<org.wixanz.omniva.foo.exception.FooNotFoundException> but was<java.lang.AssertionError>
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:28)
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:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
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:191)
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: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.AssertionError: Content type not set
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:35)
at org.springframework.test.util.AssertionErrors.assertTrue(AssertionErrors.java:65)
at org.springframework.test.web.servlet.result.ContentResultMatchers$1.match(ContentResultMatchers.java:81)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
at org.wixanz.omniva.integration.FooControllerTest.notFoundFoo(FooControllerTest.java:87)
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.ExpectException.evaluate(ExpectException.java:19)
... 28 more

NestedServletException wraps only the cause of the exception.
It is not your actual issue.
Its javadoc defines itself as :
Subclass of ServletException that properly handles a root cause in
terms of message and stacktrace, just like
NestedChecked/RuntimeException does.
Exceptions thrown in a rest controller have to be mapped to a http response. If you didn't it, Spring does that for you by throwing NestedServletException/NestedCheckedException according to the exception nature (checked or runtime).
A Java exception is not a http response.
You cannot let it be thrown as you did in a classic java code.
You have to convert it as something compatible with the http norms.
For Rest controllers you should use #ExceptionHandler and #ControllerAdvice.
#ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler(FooNotFoundException.class)
protected ResponseEntity<Object> handleFooNotFound(FooNotFoundException exception, WebRequest request) {
return handleExceptionInternal(exception, "Foo Not Found",
new HttpHeaders(), HttpStatus.NOT_FOUND, request);
}
}

Related

Getting "Null Pointer Exception" and "You cannot use argument matchers outside of verification or Stubbing" using indexAsync method in resthighlevelcl

#Repository
public class ElasticRepository {
private static final Logger LOG = LoggerFactory.getLogger(ElasticRepository.class);
#Autowired
private ElasticSearchConfig elasticSearchConfig;
#Autowired
private ObjectMapper mapper;
#Autowired
private RestHighLevelClient client;
public void ingest(UnifiedOrder unifiedClubOrder) throws ElasticsearchException, JsonProcessingException {
IndexRequest indexRequest = new IndexRequest(elasticSearchConfig.elasticSearchIndex)
.id(unifiedClubOrder.getOrderNo())
.source(mapper.writeValueAsString(unifiedClubOrder), XContentType.JSON)
.version(unifiedClubOrder.getModifyTs().getTime())
.versionType(VersionType.EXTERNAL_GTE);
ActionListener<IndexResponse> listener = new ActionListener<IndexResponse>() {
#Override
public void onResponse(IndexResponse indexResponse) {
System.out.println("Posted Successfully in ES Index :: ");
}
#Override
public void onFailure(Exception e) {
System.out.println("Failed to post in ES Index :: ");
IndexRequest errorIndexRequest = new IndexRequest(elasticSearchConfig.elasticSearchErrorIndex)
.id(unifiedClubOrder.getOrderNo())
.source(e.getMessage(), XContentType.JSON)
.version(unifiedClubOrder.getModifyTs().getTime())
.versionType(VersionType.EXTERNAL_GTE);
ActionListener<IndexResponse> errorIndexListener = new ActionListener<IndexResponse>() {
#Override
public void onResponse(IndexResponse indexResponse) {
System.out.println("Posted Successfully in ES Error Index :: ");
}
#Override
public void onFailure(Exception e) {
System.out.println("Failed to post in ES Error Index :: ");
}
};
client.indexAsync(errorIndexRequest, RequestOptions.DEFAULT, errorIndexListener);
}
};
client.indexAsync(indexRequest, RequestOptions.DEFAULT, listener);
}
}
==================================================================================
#RunWith(MockitoJUnitRunner.class)
#PrepareForTest({RestHighLevelClient.class})
public class ElasticRepositoryTest {
#Mock
private RestHighLevelClient client;
#Mock
private ObjectMapper objectMapper;
#Mock
private ElasticSearchConfig elasticSearchConfig;
#InjectMocks
private ElasticRepository elasticRepository;
#Test
public void ingest_Test() throws Exception {
UnifiedOrder unifiedClubOrder = new UnifiedOrder();
unifiedClubOrder.setOrderNo("12345");
unifiedClubOrder.setStatus("purchase");
unifiedClubOrder.setModifyTs(new Date());
when(objectMapper.writeValueAsString(unifiedClubOrder)).thenReturn(new ObjectMapper().writeValueAsString(unifiedClubOrder));
elasticSearchConfig.elasticSearchIndex = "test";
IndexRequest indexRequest = new IndexRequest(elasticSearchConfig.elasticSearchIndex)
.id(unifiedClubOrder.getOrderNo())
.source(objectMapper.writeValueAsString(unifiedClubOrder), XContentType.JSON)
.version(unifiedClubOrder.getModifyTs().getTime())
.versionType(VersionType.EXTERNAL_GTE);
PowerMockito.whenNew(IndexRequest.class).withAnyArguments().thenReturn(indexRequest);
ArgumentCaptor<IndexRequest> argumentCaptorIndexRequest = ArgumentCaptor.forClass(IndexRequest.class);
PowerMockito.doNothing().when(client).indexAsync(Mockito.any(), Mockito.any(),
Mockito.any());
elasticRepository.ingest(unifiedClubOrder);
verify(client).indexAsync(argumentCaptorIndexRequest.capture(), Mockito.any(), Mockito.any());
assertTrue(argumentCaptorIndexRequest.getValue() instanceof IndexRequest);
assertEquals("12345", ((IndexRequest) argumentCaptorIndexRequest.getValue()));
}
}
===========================================================================================
===============Detailed Exception are below =====================================
java.lang.NullPointerException
at org.elasticsearch.client.RestHighLevelClient.performRequestAsync(RestHighLevelClient.java:1525)
at org.elasticsearch.client.RestHighLevelClient.performRequestAsyncAndParseEntity(RestHighLevelClient.java:1498)
at org.elasticsearch.client.RestHighLevelClient.indexAsync(RestHighLevelClient.java:832)
at com.sams.mth.club.ingestion.repository.ElasticRepositoryTest.ingest_OnResponse_Test1(ElasticRepositoryTest.java:80)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
==================================================================================================
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced or misused argument matcher detected here:
-> at com.sams.mth.club.ingestion.repository.ElasticRepositoryTest.ingest_OnResponse_Test1(ElasticRepositoryTest.java:80)
-> at com.sams.mth.club.ingestion.repository.ElasticRepositoryTest.ingest_OnResponse_Test1(ElasticRepositoryTest.java:80)
-> at com.sams.mth.club.ingestion.repository.ElasticRepositoryTest.ingest_OnResponse_Test1(ElasticRepositoryTest.java:81)
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))
This message may appear after an NullPointerException if the last matcher is returning an object
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
when(mock.get(any())); // bad use, will raise NPE
when(mock.get(anyInt())); // correct usage use
Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.
at org.mockito.internal.runners.DefaultInternalRunner$1$1.testFinished(DefaultInternalRunner.java:70)
at org.junit.runner.notification.SynchronizedRunListener.testFinished(SynchronizedRunListener.java:56)
at org.junit.runner.notification.RunNotifier$7.notifyListener(RunNotifier.java:190)
at org.junit.runner.notification.RunNotifier$SafeNotifier.run(RunNotifier.java:72)
at org.junit.runner.notification.RunNotifier.fireTestFinished(RunNotifier.java:187)
at org.junit.internal.runners.model.EachTestNotifier.fireTestFinished(EachTestNotifier.java:38)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:331)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Adding #PowerMockIgnore({"javax.net.ssl.*"}) annotation to your Test method will ignore above exception.

Null Pointer Exception, when Writing Junit/Mockito Test cases at Controller class for Oauth, JSON response

I'm relatively new to Testing in Mockito, and I'm trying to write few test cases for Controller level testing and I'm getting Null pointer Exception when I'm running the test case. I'm Injecting mocks at controller layer and mocking the service layer methods. Please let me know, the issue
Controller Class:
#RestController
#RequestMapping(value="v1.0/authentication")
public class OauthTokenController {
//Logging
private static final Logger LOG = LoggerFactory.getLogger(OauthTokenController.class);
#Autowired
private SsasServiceImpl ssasService;
#RequestMapping(value="/oauth/token", method=RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public TokenActivationResponse grantToken(#RequestParam("username") String username, #RequestParam("password") String password, #RequestParam("grant_type") String grant_type){
TokenActivationResponse tokenActivationResponse = new TokenActivationResponse();
SecureString passwordSecured = new SecureString(password);
try{
tokenActivationResponse = ssasService.grantToken(username, passwordSecured, grant_type);
if(tokenActivationResponse == null){
throw new Exception();
}
LOG.info("Printing the response " + tokenActivationResponse);
}catch(Exception e){
LOG.error("Exception in oauth token granting controller", e);
}
return tokenActivationResponse;
}
}
SSASServiceImpl:
public class SSASServiceImpl{
public TokenActivationResponse grantToken(String username, SecureString password, String grant_type) throws IdvException {
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
body.add(USERNAME, username);
body.add(PASSWORD, (password != null) ? String.valueOf(password.getContent()) : null);
body.add(GRANT_TYPE, grant_type);
com.idv.gateway.api.ssas.rest.client.model.TokenActivationResponse tokenResponse = new com.idv.gateway.api.ssas.rest.client.model.TokenActivationResponse();
TokenActivationResponse response = new TokenActivationResponse();
tokenResponse = restProxy.sendAndReceiveToRestService(body, TOKEN, HttpMethod.POST, com.idv.gateway.api.ssas.rest.client.model.TokenActivationResponse.class);
response = transformGrantTokenResp(tokenResponse);
return response;
}
public TokenActivationResponse transformGrantTokenResp(com.idv.gateway.api.ssas.rest.client.model.TokenActivationResponse response) throws IdvException {
if (response != null) {
TokenActivationResponse resp = new TokenActivationResponse();
resp.getData().getAttributes().setAccess_token(response.getAccess_token());
resp.getData().getAttributes().setToken_type(response.getToken_type());
resp.getData().getAttributes().setExpires_in(response.getExpires_in());
resp.getData().getAttributes().setScope(response.getScope());
return resp;
} else {
IdvError error = new IdvError();
error.setTitle("Token Error");
throw new IdvException(error);
}
}
}
Test Class:
#RunWith(MockitoJUnitRunner.class)
public class OauthTokenControllerTest {
String accessToken = "d6234595-812d-40fc-b519-2e3456543";
Long expiresIn = 2905L;
String userName = "abcd";
String password = "efghijk";
String grant_type = "password";
String tokenType = "bearer";
String scope = "read write";
#Mock
SsasServiceImpl ssasService = new SsasServiceImpl();
#InjectMocks
OauthTokenController controller = new OauthTokenController();
#Before
public void setUp(){
}
TokenActivationResponse resp = new TokenActivationResponse();
#Test
public void testGrantToken() throws IdvException {
resp.getData().getAttributes().setAccess_token(accessToken);
resp.getData().getAttributes().setToken_type(tokenType);
resp.getData().getAttributes().setExpires_in(expiresIn);
resp.getData().getAttributes().setScope(scope);
SecureString sec = new SecureString(password);
Mockito.when(ssasService.grantToken(any(String.class),any(SecureString.class),any(String.class) )).thenReturn(resp);
final TokenActivationResponse response = controller.grantToken(any(String.class),any(String.class),any(String.class));
assertNotNull(response);
}
}
Exception:
Connected to the target VM, address: '127.0.0.1:60951', transport: 'socket'
16:21:38.387 [main] ERROR com.idv.gateway.controller.OauthTokenController - Exception in oauth token granting controller
java.lang.Exception: null
at com.idv.gateway.controller.OauthTokenController.grantToken(OauthTokenController.java:33)
at com.idv.gateway.controller.OauthTokenControllerTest.testGrantToken(OauthTokenControllerTest.java:61)
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.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
java.lang.AssertionError
at org.junit.Assert.fail(Assert.java:86)
at org.junit.Assert.assertTrue(Assert.java:41)
at org.junit.Assert.assertNotNull(Assert.java:712)
at org.junit.Assert.assertNotNull(Assert.java:722)
at com.idv.gateway.controller.OauthTokenControllerTest.testGrantToken(OauthTokenControllerTest.java:62)
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.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Disconnected from the target VM, address: '127.0.0.1:60951', transport: 'socket'
[MockitoHint] OauthTokenControllerTest.testGrantToken (see javadoc for MockitoHint):
[MockitoHint] 1. Unused... -> at com.idv.gateway.controller.OauthTokenControllerTest.testGrantToken(OauthTokenControllerTest.java:60)
[MockitoHint] ...args ok? -> at com.idv.gateway.controller.OauthTokenController.grantToken(OauthTokenController.java:31)
Process finished with exit code -1
I've resolved the issue:
Solution and Fix:
In my TestCase Code, I've replaced the below any(String.class):
Mockito.when(ssasService.grantToken(any(String.class),any(SecureString.class),any(String.class) )).thenReturn(resp);
final TokenActivationResponse response = controller.grantToken(any(String.class),any(String.class),any(String.class));
With (anyString()):
Mockito.when(ssasService.grantToken(anyString(),any(SecureString.class),anyString() )).thenReturn(resp);
final TokenActivationResponse response = controller.grantToken(anyString(),any(String.class),anyString());
One of these Links hepled: Mockito - Invalid use of argument matchers
Also, if you use argument matcher in mockito for one argument, make sure to use for all.

Spring boot 2 testing with binary response

I have a service that returns a zip file. It works fine in dev/prod, a simple a GET /content/{id}/zip will download the file in my browser.
#GetMapping(value = "/content/{id}/zip")
public ResponseEntity<byte[]> getContentZip(#PathVariable String id) {
byte[] zip = ...
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/zip"));
ResponseEntity<byte[]> response = new ResponseEntity<>(zip, headers, HttpStatus.OK);
return response;
}
The problem is with the test:
...
MvcResult result = restStudyMockMvc.perform(get("/content/{id}/zip", content.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType("application/zip")).andReturn();
byte[] bytes = result.getResponse().getContentAsByteArray();
assertThat(bytes).isNotEmpty();
...
It works fine with spring boot 1.5.
Since I've upgraded to spring boot 2. It gives me a "Could not find acceptable representation" exception:
11:04:21.244 [main] DEBUG i.o.v.web.ExceptionControllerAdvice - org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:287)
at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:218)
at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:82)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:119)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:870)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:870)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:66)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:166)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:166)
at io.osimis.vsol.web.StudyTest.getStudyZip(StudyTest.java:376)
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.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.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
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)
Thanks for your help :)
Maybe this is a little late, but I just had the same error and I found this question while searching for the solution.
In my case the error was that I had manually registered a HttpMessageConverter in my test.
this.mockMvc = MockMvcBuilders
...
.setMessageConverters(myJsonHttpMessageConverter)
.build();
By debugging I found out that the internal logic of Spring Mvc is:
If there is a converter configured, use only this converter.
If there is none configured, add all default converters.
Here is the relevant code from org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport:
protected final List<HttpMessageConverter<?>> getMessageConverters() {
if (this.messageConverters == null) {
this.messageConverters = new ArrayList<>();
configureMessageConverters(this.messageConverters);
if (this.messageConverters.isEmpty()) {
addDefaultHttpMessageConverters(this.messageConverters);
}
extendMessageConverters(this.messageConverters);
}
return this.messageConverters;
}
So to solve this you could either remove your custom converter so all default converters are used or - if you need it like I did - add the ByteArrayHttpMessageConverter in your test setup.
this.mockMvc = MockMvcBuilders
...
.setMessageConverters(myJsonHttpMessageConverter, new ByteArrayHttpMessageConverter())
.build();

How to test REST controller which use Pageable objec

I have a REST controller like above
#RequestMapping(value = "client", method = RequestMethod.GET, produces = "application/json")
public Page<ClientWithAddress> getAllClientsWithAddres(Pageable pageable){
return clientService.getAllClients(pageable);
}
When i try to run JUnit for it I got a NullPointerException on line with mockMvc.perform(get("/client")
#Test
public void Should_ReturnAllClients() throws Exception {
when(clientService.getAllClients(pageable)).thenReturn((page));
mockMvc.perform(get("/client"))
.andExpect(status().isOk())
Its probably, because i dont how o transfer Pageable object in test whean i call scope "/client" .
There is the stack
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
at pl.xxxx.controller.ClientControllerUnitTest.Should_ReturnAllClients(ClientControllerUnitTest.java:133)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.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:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
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:191)
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.NullPointerException
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.getArgumentResolver(HandlerMethodArgumentResolverComposite.java:135)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.supportsParameter(HandlerMethodArgumentResolverComposite.java:106)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:156)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
... 38 more
the following one works for me,
mockMvc = MockMvcBuilders
.standaloneSetup(myController)
.setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
.build();
mockMvc.perform(MockMvcRequestBuilders
.get()
I'm not sure how you are instantiating your pageable object in your class here:
#Test
public void Should_ReturnAllClients() throws Exception {
when(clientService.getAllClients(pageable)).thenReturn((page));
mockMvc.perform(get("/client"))
.andExpect(status().isOk())
But I certainly doubt it will be the same pageable object created by the call to the controller. What you probably want to do is use a matcher in your stubbing instead:
when(clientService.getAllClients(Matchers.any(Pageable.class)).thenReturn((page));
If you are using #RunWith(SpringRunner.class) and #WebMvcTest(YourControllerUnderTest.class) then also add #EnableSpringDataWebSupport

JUnit Parameterized tests not running in isolation with Mockito, Spring, Reflection and AspectJ

I have the below test class, which has been stripped to the bare minimum needed to reproduce the issue:
#RunWith(Parameterized.class)
#ContextConfiguration(locations = { "classpath:restful-service-test-context.xml" })
#DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class ResftulServiceTest {
#Autowired
#Qualifier("failedAspectTestMessage")
private String failedAspectTestMessage;
#Autowired
private ProviderService ProviderService;
private String methodName;
private Set valuesToReturnByMock;
private TestContextManager testContextManager;
public ResftulServiceTest(String methodName, String[] valuesToReturnByMockArray) {
this.methodName = methodName;
this.valuesToReturnByMock = new HashSet<>(Arrays.asList(valuesToReturnByMockArray));
}
#Parameterized.Parameters
public static Collection values() {
return Arrays.asList(new Object[][] { { "getCountries", new String[] { "GB", "US" } }, });
}
#Before
public void setUpSpringContext() throws Exception {
testContextManager = new TestContextManager(getClass());
testContextManager.prepareTestInstance(this);
}
#Test
public void testGetValues_Fail_MyException() throws Exception {
Method methodInProviderService = ProviderService.class.getDeclaredMethod(methodName);
Mockito.when(methodInProviderService.invoke(ProviderService))
.thenThrow(new MyException(failedAspectTestMessage, StatusCodeType.ERROR));
}
#Test
public void testGetValues_Fail_Exception() throws Exception {
Method methodInProviderService = ProviderService.class.getDeclaredMethod(methodName);
Mockito.when(methodInProviderService.invoke(ProviderService))
.thenThrow(new AspectException(failedAspectTestMessage));
}
}
If I run each of the tests separately, they work fine. However, if I run all of them, testGetValues_Fail_Exception fails on the Mockito line with error:
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:497)
at com<obfuscated>.ResftulServiceTest.testGetValues_Fail_Exception(ResftulServiceTest.java:111)
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:497)
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.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.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:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: com.<obfuscated>.MyException: FAILED_ASPECT_TEST_MESSAGE
... 40 more
If I replace the .thenThrow in testGetValues_Fail_MyException with .thenReturn, it all works fine, so at some point the isolation is being broken. How can I fix this problem?
Try using Mockito.reset() passing your mock. Usually this is done to prevent interaction between test. It resets the previously configured behavior of the mock. However, in your case I cannot give more details as you are using an unusual combination of Parameterized with Spring context and DirtiesContext.

Categories

Resources