Spring Unit Test - NestedServletException вместо пользовательского исключения - PullRequest
0 голосов
/ 08 апреля 2019

Я пытаюсь написать интеграционные тесты для REST API, построенного с использованием Spring MVC.Ниже приведен мой класс контроллера.

@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);
    }
}

Ниже приведен мой класс тестирования

    @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));
    }

}

Теперь, когда я пытаюсь запустить этот модульный тест, второй модульный тест терпит неудачу, говоря, что он сталкиваетсяa NestedSerlvletException, когда он ожидает InvalidIndexException

Что я делаю не так?

Обновление трассировки стека

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

Ответы [ 3 ]

1 голос
/ 27 мая 2019

/ ** * Тест для проверки, если сервер выдает ошибку при пропуске неправильной страницы * * @ 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();}}
0 голосов
/ 27 мая 2019

Вот метод теста, создающий исключение проверки ввода (неверный ввод) или нет.

  @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();

        }
    }
0 голосов
/ 22 апреля 2019

Если вам нужно утвердить исключение во время теста, используйте следующую аннотацию для метода теста.

@ Test (ожидается = InvalidIndexException.class)

Вы много читаете об этом подробнеездесь: https://www.baeldung.com/junit-assert-exception

...