gpt4 book ai didi

java - Spring Controller 单元测试抛出 NestedServletException

转载 作者:行者123 更新时间:2023-12-03 20:27:26 29 4
gpt4 key购买 nike

我有一个 Spring Controller ,它在没有数据时抛出错误。我想测试异常,这是自定义 NoDataFoundException ,但它总是抛出 org.springframework.web.util.NestedServletException
单元测试错误信息是:java.lang.Exception: Unexpected exception, expected<com.project.NoDataFoundException> but was<org.springframework.web.util.NestedServletException>
Controller 单元测试

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {MockConfiguration.class})
@WebAppConfiguration
public class ModelControllerTest{

private MockMvc mockMvc;

@Inject
private ModelController controller;

@Inject
private ResponseBuilder responseBuilder;

@Before
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}

@Test(expected = NoDataFoundException.class)
public void findAllModels_invalidRequest_throwNoDataFound() throws Exception {
when(responseBuilder.findAll(any())).thenReturn(null);
mockMvc
.perform(get("/models"))
.andExpect(status().isInternalServerError());
}

}

Controller
@GetMapping("/models")
public ResponseEntity<List<Model>> findAllModels() {
//Some Logic
dataExistenceCheck(response);
return new ResponseEntity<>(response, HttpStatus.OK);
}

private <T> void dataExistenceCheck(T target) {
if (target == null || (target instanceof Collection && ((Collection<?>) target).isEmpty())) {
throw new NoDataFoundException();
}
}

NoDataFoundException 类
public class NoDataFoundException extends RuntimeException {

private static final long serialVersionUID = 140836818081224458L;

public NoDataFoundException() {
super();
}

public NoDataFoundException(String message) {
super(message);
}

}

寻找

我调试了代码并跟踪到 org.springframework.web.servlet.FrameworkServlet类(class)。是的,我期待 NoDataFoundException但它在那里抛出 NesteServletException .

我该如何解决?我做错了什么?

enter image description here

编辑问题

我有 @ControllerAdvice和处理 NoDataFoundException ,但它命中 NestedServletException在到达这里之前。
@ResponseBody
@ResponseStatus(value = HttpStatus.NOT_FOUND)
@ExceptionHandler(NoDataFoundException.class)
public ResponseEntity<ErrorResponse> noDataFoundExceptionHandler(NoDataFoundException exception) {
LOGGER.debug("No data found exception [{}].", exception);
return new ResponseEntity<>(new ErrorResponse("not found"), HttpStatus.NOT_FOUND);
}

最佳答案

NestedServletException是一个包装器/适配器,它采用了 javax.servlet.ServletException 的所有异常(exception)情况.它是 java servlet API 的一部分。

您可以通过以下方式解决:

1) catch NestedServletException并重新抛出原因:

try {
mockMvc
.perform(get("/models"))
.andExpect(status().isInternalServerError());
} catch (NestedServletException e) {
throw e.getCause();
}

2) 使用 org.assertj.core.api.Assertions.assertThatThrownBy
@Test
public void findAllModels_invalidRequest_throwNoDataFound() throws Throwable {
Assertions.assertThatThrownBy(() ->
mockMvc.perform(get("/models")).andExpect(status().isInternalServerError()))
.hasCause(new NoDataFoundException(null));
}

3) 在您的 Controller 或全局异常处理程序中添加 @ExceptionHandler(NoDataFoundException.class)并将其转换为有效的 Http 代码和响应正文。

4) 扩展 NoDataFoundException来自 ServletException

关于java - Spring Controller 单元测试抛出 NestedServletException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58056115/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com