使用 Junit 5 和 MockMvc 类进行 Spring MVC 错误处理

问题描述 投票:0回答:1

这篇文章是在 Spring MVC 3 中执行错误处理。

我的测试用例没有测试下面提到的错误场景。

我的控制器类 -

@RestController
public class CPCommonServiceController {

    @Autowired
    private MyCommonService MyCommonService;

    @RequestMapping(method = {RequestMethod.GET}, value = "/data", headers = "Accept=application/json")
    public List<Dto> getData() throws ServiceException {
        return myCommonService.getData();
    }
}

测试课-

public class MyControllerTest {
    @InjectMocks
    private MyController myController;

    @Mock
    private MyCommonService myCommonService;

    private MockMvc mockMvc;

    @BeforeEach
    public void setup() {
        MockitoAnnotations.openMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup
                (new MyCommonServiceController()).build();
    }
 @Test
    public void testDataThrowServiceException() throws Exception {
        when(myCommonService.getData())
                .thenThrow(ServiceException.class);

        mockMvc.perform(get("/data"))
                .andExpect(MockMvcResultMatchers.status().is4xxClientError());
    }
}

发生错误-

jakarta.servlet.ServletException: Request processing failed: com.exception.ServiceException

    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1022)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:903)
    at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:564)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:885)
spring spring-mvc junit5 spring-mvc-test
1个回答
0
投票

这是我解决此错误的方法---

我已经更新了我的

MyControllerTest
setUp()
方法如下:

public void setUp() {
        MockitoAnnotations.openMocks(this);
        this.mockMvc = MockMvcBuilders.standaloneSetup(cpCommonServiceController)
                .setHandlerExceptionResolvers(getSimpleMappingExceptionResolver())
                .build();

    }

还有一个新的

ExceptionResolver
方法

SimpleMappingExceptionResolver getSimpleMappingExceptionResolver() {

SimpleMappingExceptionResolver result
        = new SimpleMappingExceptionResolver();

// Setting customized exception mappings
Properties p = new Properties();
p.put(SimpleMappingExceptionResolver.class.getName(), "Errors/Exception");
result.setExceptionMappings(p);

// Unmapped exceptions will be directed there
result.setDefaultErrorView("Errors/Default");

// Setting a default HTTP status code
result.setDefaultStatusCode(HttpStatus.BAD_REQUEST.value());

return result;

}

© www.soinside.com 2019 - 2024. All rights reserved.