2

I am trying to write integration tests for REST API built using Spring MVC. Following is my controller class.

@RestController
@RequestMapping("/api")
public class ZoningToolRestController {

    @Autowired
    ImageProcessingService service;

    @RequestMapping(value = "/page/{index}", produces = "image/png", method = RequestMethod.GET)
    public byte[] getPage(@PathVariable("index") int index) throws InvalidIndexException, IOException {

        return service.getPage(index);
    }

    @ExceptionHandler
    public ResponseEntity<Map<String, Object>> handleException(Exception e) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("error", e.getMessage());

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return new ResponseEntity<Map<String, Object>>(map, headers, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

Following is my test class

    @RunWith(SpringRunner.class)
@SpringBootTest
public class ZoningToolRestControllerTests {

    private MockMvc mvc;

    @Autowired
    private ZoningToolRestController zoningToolRestController;

    @Before
    public void setup() {
        this.mvc = MockMvcBuilders.standaloneSetup(zoningToolRestController)
                .setHandlerExceptionResolvers(getExceptionResolver())
                .build();
    }

    private HandlerExceptionResolver getExceptionResolver() {

        ExceptionHandlerExceptionResolver exceptionResolver = new ExceptionHandlerExceptionResolver();
        exceptionResolver.setMappedHandlerClasses(InvalidIndexException.class, ExceptionHandler.class);

        return exceptionResolver;
    }

    /**
     * Test to check if image is returned in case of valid call
     * 
     * @throws Exception
     */
    @Test
    public void givenDocument_whenGetValidPage_thenSuccess() throws Exception {

        mvc.perform(get("/api/page/1").accept(MediaType.IMAGE_PNG)).andExpect(status().isOk())
                .andExpect(content().contentTypeCompatibleWith(MediaType.IMAGE_PNG));
    }

    /**
     * Test to check if server throws an error when wrong page is passed
     * 
     * @throws Exception
     */
    @Test
    public void givenDocument_whenGetWrongPage_thenError() throws Exception {
        mvc.perform(get("/api/page/11").accept(MediaType.IMAGE_PNG)).andExpect(status().isInternalServerError())
                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON));
    }

}

Now when I am trying to run this unit test, the second unit test is failing saying it is encountering a NestedSerlvletException when it is expecting a InvalidIndexException

What am I doing wrong?

Update Stack Trace

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is in.co.dhdigital.zoningtool.processors.InvalidIndexException: Invalid index passed.
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1013)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:71)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    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:182)
    at in.co.dhdigital.zoningtool.test.controllers.ZoningToolRestControllerTests.givenDocument_whenGetWrongPage_thenError(ZoningToolRestControllerTests.java:73)
    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.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Caused by: in.co.dhdigital.zoningtool.processors.InvalidIndexException: Invalid index passed.
    at in.co.dhdigital.zoningtool.processors.impl.TiffImageProcessor.getPage(TiffImageProcessor.java:53)
    at in.co.dhdigital.zoningtool.services.ImageProcessingService.getPage(ImageProcessingService.java:32)
    at in.co.dhdigital.zoningtool.controllers.ZoningToolRestController.getPage(ZoningToolRestController.java:34)
    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:189)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    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:800)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
    ... 41 more
Pavan Andhukuri
  • 1,547
  • 3
  • 23
  • 49
  • Did you go through : https://stackoverflow.com/questions/35406030/what-is-the-origin-of-a-nestedservletexception/35407289 – R.G Apr 08 '19 at 10:36
  • Could you please provide the full stack trace? – mle Apr 08 '19 at 11:40
  • @RanjitGopinathan Yes I did.. but that has nothing to do with my question.. – Pavan Andhukuri Apr 12 '19 at 12:07
  • @mle added stack trace – Pavan Andhukuri Apr 12 '19 at 12:09
  • I don't think you need to define your exception handler on the test setup as you have it defined inside of your controller. https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/handler/AbstractHandlerExceptionResolver.html#setMappedHandlerClasses-java.lang.Class...- – Tiarê Balbi Apr 22 '19 at 05:45

3 Answers3

3

/** * Test to check if server throws an error when wrong page is passed * * @throws Exception */

  @Test(expected= InvalidIndexException.class)
    public void givenDocument_whenGetWrongPage_thenError() throws Exception {
        try{
mvc.perform(get("/api/page/11").accept(MediaType.IMAGE_PNG)).andExpect(status().isInternalServerError())
                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON));
    }catch (NestedServletException e) {
            throw (Exception) e.getCause();}}
MangduYogii
  • 935
  • 10
  • 24
  • When I use `expected`, it's an invalid parameter. Did you know an equivalent that work with jupiter (org.junit.jupiter.api.Test)? – MrSolarius Dec 23 '22 at 10:19
0

If you need to assert an Exception during test , please use the following annotation for the test method.

@Test(expected = InvalidIndexException.class)

You many read more about this here : https://www.baeldung.com/junit-assert-exception

R.G
  • 6,436
  • 3
  • 19
  • 28
0

Here is the test method throw an input validation (Bad input) exception or not.

  @Test(expected = ConstraintViolationException.class)
    public void addBadInput() throws Exception {
        try {
            mockMvc.perform(post(URL).content(object_mapper.writeValueAsString(bad_input_val)).
                    accept(MediaType.APPLICATION_JSON_VALUE)).andExpect(status().isBadRequest());
        } catch (NestedServletException e) {
            throw (Exception) e.getCause();

        }
    }
MangduYogii
  • 935
  • 10
  • 24