```java
#RunWith(SpringRunner.class)
#SpringBootTest(classes = DemoApplication.class)
#AutoConfigureMockMvc
#TestPropertySource(locations = "classpath:application-integrationtest.properties")
#EnableAutoConfiguration(exclude = {WebMvcAutoConfiguration.class})
public class DemoControllerTest {
#Autowired
private MockMvc mvc;
#Autowired
private WebApplicationContext context;
#Before
public void setup() {
this.mvc = MockMvcBuilders.webAppContextSetup(context).dispatchOptions(true).build();
}
#Test
public void getApplicationVersionTest() throws Exception {
mvc.perform(get("/demo/version").contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
}
I have upgraded my springboot version from v2.1.7 to v2.2.5 and since then my controller tests are failing because the mock is returning 404 for all. I have excluded WebMvcAutoConfiguration class for bean instantiation error. Now the mock returns 404 for all.
Error Trace:
java.lang.AssertionError: Status expected:<200> but was:<404>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:59)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:122)
at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:627)
at org.springframework.test.web.servlet.result.StatusResultMatchers$$Lambda$879.0000000014CC94F0.match(Unknown Source)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:196)
at com.demo.controller.ControllerTest.getApplicationVersionTest(ControllerTest.java:67)
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.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.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:40)
at org.junit.vintage.engine.VintageTestEngine$$Lambda$249.0000000011B25800.accept(Unknown Source)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:496)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:486)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:241)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:80)
at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:71)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
at org.junit.platform.launcher.core.DefaultLauncher$$Lambda$209.0000000011A9CB80.accept(Unknown Source)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.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 have upgraded my Spring Boot version from v2.1.7 to v2.2.5 and since then my controller tests are failing because the mock is returning 404 for all. I have excluded `WebMvcAutoConfiguration` class for bean instantiation error. Now the mock returns 404 for all.
Below is the my controller class:
#PropertySource(ignoreResourceNotFound = true, value = "classpath:app-version.properties")
#RestController
#RequestMapping("/demo")
public class DemoController extends CommonController {
private static final Logger LOGGER = LoggerFactory.getLogger(DemoController.class);
private DemoService demoService;
#Value("${environment.name:unknown}")
private String environmentName;
#Value("${buildNumber:unknown}")
private String buildNumber;
private EovService eovService;
#Autowired
public DemoController(DemoService demoService, EovService eovService) {
this.demoService = demoService;
this.eovSqsService = eovSqsService;
}
#GetMapping(value = "/version", produces = {"application/json"}, consumes = {
"application/json"})
public ResponseEntity getApplicationVersionNumber() {
String result = environmentName + " " + buildNumber;
return new ResponseEntity<>(result, HttpStatus.OK);
}
}
Below is what I receive in my console for mockServletResponse. The controller class is starting as expected but the mockMvc is receiving 404 response for all the requests.
12:09:52.247 [] [scheduling-1] INFO
c.t.r.c.h.HeartbeatBatchScheduler - [HEALTH_CHECK][RTCA][svc-demo-status][LOCAL][UP]
12:09:52.254 [] [main] INFO
c.t.r.c.n.c.DemoControllerTest - Started DemoControllerTest in 12.598 seconds (JVM running for 14.864)
12:09:52.398 [] [main] DEBUG
c.t.r.s.j.s.AbstractJWTCommonFilter - In DoFilter JWT Authentication class
MockHttpServletRequest:
HTTP Method = GET
Request URI = /demo/version
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8"]
Body = null
Session Attrs = {}
Handler:
Type = null
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 404
Error message = null
Headers = []
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
12:09:52.468 [] [SpringContextShutdownHook] DEBUG
o.a.h.i.c.PoolingHttpClientConnectionManager - Connection manager is shutting down
12:09:52.469 [] [SpringContextShutdownHook] DEBUG
o.a.h.i.c.PoolingHttpClientConnectionManager - Connection manager shut down
Related
I have table of users as shown:
Rest controller method for delete user is:
#RequestMapping(APP_USER_API_PATH)
#RestController
#RequiredArgsConstructor
public class AppUserControllerImpl implements AppUserController {
#NonNull
private final AppUserService appUserService;
#NonNull
private final AppUserMapper appUserMapper;
#Override
#DeleteMapping("/{id}")
public ResponseEntity<?> delete(#PathVariable("id") Long id) {
if(appUserService.findById(id).isEmpty())
throw new EntityNotFoundException(String.format("Record not found with id = %s", id));
// If Found then
appUserService.deleteById(id);
return ResponseEntity.status(HttpStatus.OK).body(
String.format("Record with id = %s deleted", id)
);
}
}
Test class and method is as follows:
#SpringBootTest
#AutoConfigureMockMvc
#RunWith(SpringRunner.class)
public class AppUserControllerImplTest {
private static final String ENDPOINT_URL = APP_USER_API_PATH;
#InjectMocks
private AppUserControllerImpl appuserController;
#Mock
private AppUserService appuserService;
#Mock
private AppUserMapper appuserMapper;
#Autowired
private MockMvc mockMvc;
#Before
public void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(this.appuserController).build();
}
#Test
public void delete() throws Exception {
Mockito.doNothing().when(appuserService).deleteById(ArgumentMatchers.anyLong());
mockMvc.perform(
MockMvcRequestBuilders.delete(ENDPOINT_URL + "/" + 1L + ""))
.andExpect(MockMvcResultMatchers.status().isOk());
Mockito.verify(appuserService, Mockito.times(1)).deleteById(Mockito.anyLong());
Mockito.verifyNoMoreInteractions(appuserService);
}
}
it always throws exception:
Caused by: javax.persistence.EntityNotFoundException: Record not found with id = 1
and the test always fails even if record with id = 1 exists.
Full StackTrace:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.persistence.EntityNotFoundException: Record not found with id = 1
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
at org.springframework.web.servlet.FrameworkServlet.doDelete(FrameworkServlet.java:931)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:72)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
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:201)
at pk.team.inlab.web.app.profile2.controller.impl.AppUserControllerImplTest.delete(AppUserControllerImplTest.java:141)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
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.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:366)
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$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
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$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Caused by: javax.persistence.EntityNotFoundException: Record not found with id = 1
at pk.team.inlab.web.app.profile2.controller.impl.AppUserControllerImpl.delete(AppUserControllerImpl.java:89)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1071)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:964)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
... 43 more
The issue is happening because you have not mocked the findById method of AppUserService class
You have written the following piece of code
if(appUserService.findById(id).isEmpty()) throw new EntityNotFoundException(String.format("Record not found with id = %s", id));
which throws as exception if the item with this id is not found.
In the test class, you have mocked the AppUserService using
#Mock
private AppUserService appuserService;
however, you have not told the Mock framework what to do when the findById method is called.
Add a Mockito.when statement to your test case for example in the following format
Mockito.when(appUserService.findById(ArgumentMatchers.anyLong())).thenReturn("***Return a dummy object here ***")
This should let the mock framework know that it should return the dummy result when this method is called and that should prevent the exception from being thrown.
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.
I have a problem with my Unit Tests for a spring Rest application. In my Unit Tests I always get the problem that I get 401 "Unauthorized" as responsestatus and I don't know how to solve this problem.
My Security config is this:
#Configuration
#EnableWebSecurity
#Order(1)
public class ApiSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private ApiKeyRepository apiKeyRepository;
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
ApiKeyAuthFilter filter = new ApiKeyAuthFilter(Globals.HEADER_APIKEY);
filter.setAuthenticationManager(authentication -> {
String principal = (String) authentication.getPrincipal();
Optional<ApiKey> apiKey = apiKeyRepository.findByApiKey(principal);
if (!apiKey.isPresent()) {
throw new BadCredentialsException("The API key was not found or not the expected value.");
}
authentication.setAuthenticated(true);
return authentication;
});
httpSecurity.
csrf().disable().
addFilter(filter).authorizeRequests().anyRequest().authenticated().and().
regexMatcher("(?i)/api/v1/(?:print|resource)(?:/|$).*").
sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
My Unit Test looks like:
#RunWith(SpringRunner.class)
#WebMvcTest(ResourceController.class)
public class ResourceControllerTestGetByLogicalFileNameOrDate {
#Autowired
private MockMvc mvc;
#Autowired
private ResourceRepository resourceRepositoryMock;
private Resource setNewResource(long fileSize, String hash, String logicalFileName) {
return getResource(fileSize, hash, logicalFileName);
}
#Test
public void testGetResourceByLogicalFileNameOrDateWithNoInput() throws Exception {
mvc.perform(get(String.format("/api/v1/resource/find/%s", ""))
.header(Globals.HEADER_APIKEY, "lEcsQI09MjUTCMQ5IVvSjf4Anxt+c4nhZAMnU1yDmVI=")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest());
}
I always get the problem that my tests failed. As response I get:
2018-05-07 09:26:52.003 INFO 18692 --- [ main] o.s.b.t.m.w.SpringBootMockServletContext : Initializing Spring FrameworkServlet ''
2018-05-07 09:26:52.003 INFO 18692 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : FrameworkServlet '': initialization started
2018-05-07 09:26:52.005 INFO 18692 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : FrameworkServlet '': initialization completed in 2 ms
java.lang.AssertionError: Status
Expected :400
Actual :401
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:55)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:82)
at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:617)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:178)
at at.techsoft.iprint.nano.services.resource.ResourceControllerTestGetByLogicalFileNameOrDate.testGetResourceByLogicalFileNameOrDateWithNoInput(ResourceControllerTestGetByLogicalFileNameOrDate.java:83)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
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.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Can i turn off the security for the tests? Please can anyone help me to solve this.
When I use the Annotation #ActiveProfiles(value = "test") I get the Exception:
MockHttpServletRequest:
HTTP Method = GET
Request URI = /api/v1/resource/find
Parameters = {logicalFileName=[Res]}
Headers = {Content-Type=[application/json], X-NANO-APIKEY=[]}
Body = <no character encoding set>
Session Attrs = {SPRING_SECURITY_SAVED_REQUEST=DefaultSavedRequest[http://localhost/api/v1/resource/find?logicalFileName=Res]}
Handler:
Type = null
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 401
Error message = Unauthorized
Headers = {WWW-Authenticate=[Basic realm="Realm"], X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY]}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Status
Expected :200
Actual :401
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:55)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:82)
at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:617)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:178)
at at.techsoft.iprint.nano.services.resource.ResourceControllerTestGetByLogicalFileNameOrDate.testGetResourceByLogicalFileNameOrDateWithCorrectLogicalFileName(ResourceControllerTestGetByLogicalFileNameOrDate.java:88)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Since I use Spring Boot 1, I solved it this way:
#WebMvcTest(value = ResourceController.class, secure = false)
Please note that for the newer version of Spring Boot 2 the secure option is not available anymore, so use this:
#WebMvcTest(value = ResourceController.class, excludeAutoConfiguration = {SecurityAutoConfiguration.class})
Looks like your security is the one causes issue. You can use Spring Profile( like #Profile("Production")) as follows:
#Configuration
#EnableWebSecurity
#Profile("Production")
#Order(1)
public class ApiSecurityConfig{
...
}
#RunWith(SpringRunner.class)
#WebMvcTest(ResourceController.class)
#ActiveProfile("test")
public class ResourceControllerTestGetByLogicalFileNameOrDate {
...
}
Reference : https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html
Since in local tests you wouldn't want that to be configured, you can use #ActiveProfiles("test") while running the tests. this way, the configurations won't be loaded for local tests.
please could help to me with Spring testing with MockMvc.
I have Controller(I deleted path code of metod)
#Controller
#RequestMapping("/read/object-attributes")
public class GroupAttributeReadController {
#Autowired
private GroupAttributeService groupAttributeService;
#RequestMapping(value = "/import", method = RequestMethod.GET)
public
#ResponseBody
GroupAttributeBufferListResponse findAll(#RequestParam(value = "pageNum", required = true) int pageNum,
#RequestParam(value = "pageSize", required = true) int pageSize,
#RequestParam(value = "order", required = false) String order,
#RequestParam(value = "orderDir", required = false) String orderDir,
#RequestParam(value = "loadSession") Long loadSession,
#RequestParam( value = "showCorrect", defaultValue = "0") Integer showCorrect,
#RequestParam(value="naviUser") String user,
#RequestParam Map<String, String > params,
HttpServletResponse response, Locale locale) {
}
And my test
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
public class ControllersTest {
#Autowired
WebApplicationContext wac;
MockMvc mockMvc;
#Before
public void setup() {
DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
this.mockMvc = builder.build();
}
#Test
public void testController() throws Exception {
ResultMatcher ok = MockMvcResultMatchers.status().isOk();
MockHttpServletRequestBuilder request = MockMvcRequestBuilders.get("/read/object-attributes/import?pageNum=2&pageSize=5&order=test&orderDir=DESC&loadSession=1&showCorrect=0&naviUser=user&FILTER_Test=Test");
this.mockMvc.perform(request)
.andExpect(ok);
}
}
But I'm not understand why response 404. Maybe I something forget? Maybe need config-file, I dont know :(
java.lang.AssertionError: Status
Expected :200
Actual :404
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81)
at org.springframework.test.web.servlet.result.StatusResultMatchers$10.match(StatusResultMatchers.java:665)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
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:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
You need to provide the required params.
Example:
#Test
public void testAddInformation() throws Exception {
this.mockMvc.perform(post("/sample").param("name", "provideName").param("address", "provideAddress")).andExpect(status().isOk());
};
You should include #ContextConfiguration as well - here is a snippet from #WebAppConfiguration documentation:
Note that #WebAppConfiguration must be used in conjunction with
#ContextConfiguration, either within a single test class or within a test class hierarchy.
So your test class should look something like that:
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration( classes = AppConfig.class, WebConfig.class )
public class ControllersTest {
(...)
}
I have rest service(PUT) which I intend to unit test it. I am using RestEasy for the Rest calls.
Here is my Resource :
#Path("/my_person")
public class MyResource {
private MyDAO myDao;
#Inject
public MyResource(MyDao myDao) {
this.myDao = myDao;
}
#PUT
#Timed
#Path("purchase_number/{purchaseNumber}/amount/{amount}/number_of_items")
#Produces(MediaType.APPLICATION_JSON)
public Response getItems(#PathParam("purchaseNumber") String purchaseNumber,
#PathParam("amount") String amount) {
return Response.ok(String.format("{\"items\": %d}", myDao.getItems(purchaseNumber, amount))).build();
}
}
The myDao.getItems returns an integer.
My Test class is as follows :
#RunWith(MockitoJUnitRunner.class)
public class MyResourceTest {
#Mock
private MyDao myDao;
#InjectMock
private MyResource myResource;
private TJWSEmbeddedJaxrsServer server;
private ResteasyClient resteasyClient;
#Before
public void startServer() throws IOException {
resteasyClient = new ResteasyClientBuilder().build();
server = new TJWSEmbeddedJaxrsServer();
server.setPort(PORT);
server.setBindAddress("localhost");
server.getDeployment().getResources().add(myResource);
server.start();
}
#After
public void stopServer() {
if (server != null) {
server.stop();
server = null;
}
}
#Test
public void testWhenValidInputGiven() {
String purchaseNumber = "A57697DF";
String amount = "340";
when(myDao.getItems(purchaseNumber, amount)).thenReturn(10);
Response response = resteasyClient.target("http://localhost:9980/my_person/purchase_number/{purchaseNumber}/amount/{amount}/number_of_items").request().buildPut(Entity.entity("{}", MediaType.APPLICATION_JSON))).invoke();
String text = response.getEntity().toString();
assertEquals(200, resp.getStatus());
assertEquals("{\"items\": 10}", text);
}
}
I get the following error at String text = response.getEntity().toString() since the entity object is null. So does it mean that it didn't create the request at all?
java.lang.NullPointerException
at resources.MyResourceTest.testWhenValidInputGiven(MyResourceTest.java:126)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
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.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
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.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
at org.jboss.resteasy.core.SynchronousDispatcher.writeResponse(SynchronousDispatcher.java:427)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:376)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:179)
at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:220)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:56)
at org.jboss.resteasy.plugins.server.tjws.TJWSServletDispatcher.service(TJWSServletDispatcher.java:40)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:51)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at Acme.Serve.Serve$ServeConnection.runServlet(Serve.java:2331)
at Acme.Serve.Serve$ServeConnection.parseRequest(Serve.java:2285)
at Acme.Serve.Serve$ServeConnection.run(Serve.java:2057)
at Acme.Utils$ThreadPool$PooledThread.run(Utils.java:1402)
at java.lang.Thread.run(Thread.java:745)
Have you tried to put / in front of you method path #Path("/purchase_number/{purchaseNumber}/amount/{amount}/number_of_items")
i think the framework misunderstood your path and expect my_personpurchase_number/.
Check your status code on response to see if actually get 200 back or a 404.
The solution to this problem was that I was using
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>1.1.1</version>
</dependency>
instead of
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>jaxrs-api</artifactId>
<version>3.0.10.Final</version>
</dependency>
both had the class javax.ws.rs.core.Response.