@ControllerAdvice中的异常处理程序方法不会被调用

时间:2018-04-19 10:23:52

标签: spring spring-mvc exception-handling junit5

我使用junit5测试我的控制器。在测试方法中,抛出EntityNotFoundException但不调用异常处理程序。 我尝试用命令1声明ExceptionHandlerExceptionResolver bean。但它没有用。

处理EntityNotFoundException的异常处理程序:

@ControllerAdvice
@EnableWebMvc
public class AppWideExceptionHandler {

    @ExceptionHandler(EntityNotFoundException.class)
    public @ResponseBody
    String handleEntityNotFoundException(EntityNotFoundException e) {
        return "test";
    }
    ...
}

AppWideExceptionHandler位于youshu.exception个包中,由于@ComponentScan({"youshu.controller", "youshu.service","youshu.exception"})WebConfig注释,我们会对其进行扫描。

processRefundApplication控制器方法调用RefundService.get(String orderID)可能会抛出EntityNotFoundException

@Controller
@RequestMapping("/Order")
public class OrderController {
    @AsSeller
    @RequestMapping(value = "/{orderID}/RefundApplication",
            method = RequestMethod.PATCH,
            params = "isApproved",
            produces = "application/json")
    @Transactional(rollbackFor = RuntimeException.class)
    public @ResponseBody
    Map processRefundApplication(@SessionAttribute("user") User user,
                                 @PathVariable("orderID") String orderID,
                                 @RequestParam("isApproved") boolean isApproved) {
        ...
    }

调试信息:

...
17:58:34.575 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - Returned connection 5312115 to pool.
17:58:34.576 [main] DEBUG org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Resolving exception from handler [public java.util.Map youshu.controller.OrderController.processRefundApplication(youshu.entity.User,java.lang.String,boolean)]: youshu.exception.EntityNotFoundException: 找不到订单ID为20180419182220001的退款申请
17:58:34.576 [main] DEBUG org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver - Resolving exception from handler [public java.util.Map youshu.controller.OrderController.processRefundApplication(youshu.entity.User,java.lang.String,boolean)]: youshu.exception.EntityNotFoundException: 找不到订单ID为20180419182220001的退款申请
17:58:34.576 [main] DEBUG org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Resolving exception from handler [public java.util.Map youshu.controller.OrderController.processRefundApplication(youshu.entity.User,java.lang.String,boolean)]: youshu.exception.EntityNotFoundException: 找不到订单ID为20180419182220001的退款申请
17:58:34.577 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Could not complete request
youshu.exception.EntityNotFoundException: 找不到订单ID为20180419182220001的退款申请
    at youshu.service.RefundService.get(RefundService.java:23) ~[classes/:?]
    ...

测试类:

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {WebConfig.class, RootConfig.class, DataConfig.class})
@WebAppConfiguration
class OrderControllerTest {
    @Autowired
    OrderController controller;
    @Autowired
    UserService userService;
    @Autowired
    OrderService orderService;
    private User customer;
    private User seller;
    private HashMap<String, Object> sessionAttrs;
    private ResultMatcher success = jsonPath("$.code")
            .value("0");
    private MockMvc mockMvc;
    @BeforeEach
    void init() {
        if (customer == null) {
            customer = new User();
            customer.setID(18222);
            customer.setName("shijiliyq");
            customer.setPassword("...");
            customer.setPaymentPassword("...");
        }
        if (seller == null) {
            seller = new User();
            seller.setID(27895);
        }
        if (sessionAttrs == null) {
            sessionAttrs = new HashMap<>();
            sessionAttrs.put("user", customer);
        }
        if (mockMvc == null)
            mockMvc = standaloneSetup(controller).build();

    }
    @Test
    void processRefundApplication() throws Exception{
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

        String path = String.format("/Order/%s%d0001/RefundApplication"
                , simpleDateFormat.format(new Date()), customer.getID());
        HashMap<String,Object> sessionAttributes=new HashMap<>();
        sessionAttributes.put("user",seller);
        mockMvc.perform(patch(path)
                .characterEncoding("UTF-8")
                .param("isApproved","true")
                .sessionAttrs(sessionAttributes))
                .andDo(print())
                .andExpect(success);
    }
    ...
}

1 个答案:

答案 0 :(得分:0)

您需要将mockMvc实例指向控制器建议类:

@Autowired
AppWideExceptionHandler exceptionHandler;

...

mockMvc = standaloneSetup(controller).setControllerAdvice(exceptionHandler).build();